-- 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;

-- 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
);