-- client_management_system_fixed.sql
-- Database: client_management_system
-- Created: 2024

-- Create the database
CREATE DATABASE IF NOT EXISTS client_management_system;
USE client_management_system;

-- Users table for authentication
CREATE TABLE IF NOT EXISTS users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    full_name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    department ENUM('lead', 'sales', 'delivery', 'project', 'upfollow', 'admin') NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Clients table
CREATE TABLE IF NOT EXISTS clients (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    phone VARCHAR(20) NOT NULL,
    package ENUM('free', 'paid') NOT NULL,
    note TEXT,
    country VARCHAR(50),
    current_department ENUM('lead', 'sales', 'delivery', 'project', 'upfollow', 'completed') DEFAULT 'lead',
    status ENUM('pending', 'in_progress', 'completed') DEFAULT 'pending',
    payment_status ENUM('pending', 'collected') DEFAULT 'pending',
    assigned_to INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL
);

-- Client history tracking
CREATE TABLE IF NOT EXISTS client_history (
    id INT PRIMARY KEY AUTO_INCREMENT,
    client_id INT NOT NULL,
    from_department ENUM('lead', 'sales', 'delivery', 'project', 'upfollow', 'completed'),
    to_department ENUM('lead', 'sales', 'delivery', 'project', 'upfollow', 'completed'),
    action_by INT NOT NULL,
    notes TEXT,
    action_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE,
    FOREIGN KEY (action_by) REFERENCES users(id) ON DELETE CASCADE
);

-- Insert default admin user with CORRECT PASSWORD HASH for 'admin123'
INSERT INTO users (username, password, full_name, email, department) VALUES
('admin', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'System Administrator', 'admin@system.com', 'admin'),
('lead_user', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'Lead Manager', 'lead@company.com', 'lead'),
('sales_user', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'Sales Manager', 'sales@company.com', 'sales'),
('delivery_user', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'Delivery Manager', 'delivery@company.com', 'delivery'),
('project_user', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'Project Manager', 'project@company.com', 'project'),
('upfollow_user', '$2y$12$7Y6JvL8QzNk5HtR9wXcB4uC2dF3gH5jK7L9M1N3P5R7T9V1X3Z5B7D9F1H3J5L', 'Upscale Manager', 'upfollow@company.com', 'upfollow');