-- Expenses module tables

CREATE TABLE IF NOT EXISTS expense_categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS expenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    date DATE NOT NULL,
    category_id INT NOT NULL,
    amount DECIMAL(15,2) NOT NULL,
    reference VARCHAR(100),
    description TEXT,
    vendor VARCHAR(100),
    payment_method ENUM('Cash', 'Bank Transfer', 'Credit Card', 'Check', 'Other') DEFAULT 'Cash',
    receipt_file VARCHAR(255),
    user_id INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (category_id) REFERENCES expense_categories(id) ON DELETE RESTRICT
);

-- Seed default categories
INSERT INTO expense_categories (name, description) VALUES
('Office Supplies', 'Pens, paper, toner, etc.'),
('Travel', 'Flights, hotels, transport'),
('Meals & Entertainment', 'Client lunches, team events'),
('Utilities', 'Electricity, water, internet'),
('Rent', 'Office rent'),
('Salaries', 'Employee salaries'),
('Maintenance', 'Repairs and maintenance'),
('Advertising', 'Marketing and ads'),
('Software', 'Subscriptions and licenses'),
('Other', 'Miscellaneous expenses');

-- Add permissions
INSERT IGNORE INTO user_permissions (user_id, page, can_view, can_add, can_edit, can_delete)
SELECT id, 'expenses', 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0) 
FROM users;

INSERT IGNORE INTO user_permissions (user_id, page, can_view, can_add, can_edit, can_delete)
SELECT id, 'expense_settings', 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0), 
    IF(role = 'admin', 1, 0) 
FROM users;
