-- Create quarterly_orders table for managing Sabbath School quarterly orders
CREATE TABLE quarterly_orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    quarterly_type VARCHAR(50) NOT NULL CHECK (quarterly_type IN ('Regular', 'Teachers', 'Large Print', 'EG White Notes')),
    amount INTEGER NOT NULL CHECK (amount > 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Create index on name for faster searching
CREATE INDEX idx_quarterly_orders_name ON quarterly_orders(name);

-- Create index on quarterly_type for filtering
CREATE INDEX idx_quarterly_orders_type ON quarterly_orders(quarterly_type);

-- Create trigger to automatically update updated_at column
CREATE OR REPLACE FUNCTION update_quarterly_orders_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_quarterly_orders_updated_at
    BEFORE UPDATE ON quarterly_orders
    FOR EACH ROW
    EXECUTE FUNCTION update_quarterly_orders_updated_at();