-- =============================================
-- LICENSE MANAGEMENT SYSTEM - DATABASE SETUP
-- =============================================

CREATE DATABASE IF NOT EXISTS license_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE license_system;

-- Plans Table
CREATE TABLE IF NOT EXISTS plans (
    id INT AUTO_INCREMENT PRIMARY KEY,
    product_type ENUM('AMS', 'CMS') NOT NULL,
    plan_name VARCHAR(100) NOT NULL,
    duration_months INT NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Clients Table
CREATE TABLE IF NOT EXISTS clients (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    phone VARCHAR(20) NOT NULL,
    business_name VARCHAR(200) NOT NULL,
    domain VARCHAR(200) NOT NULL,
    email VARCHAR(200),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- License Keys Table
CREATE TABLE IF NOT EXISTS license_keys (
    id INT AUTO_INCREMENT PRIMARY KEY,
    client_id INT NOT NULL,
    license_key VARCHAR(100) NOT NULL UNIQUE,
    product_type ENUM('AMS', 'CMS') NOT NULL,
    plan_id INT NOT NULL,
    status ENUM('active', 'expired', 'suspended') DEFAULT 'active',
    activation_date DATE,
    expiry_date DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (client_id) REFERENCES clients(id),
    FOREIGN KEY (plan_id) REFERENCES plans(id)
);

-- Payments Table
CREATE TABLE IF NOT EXISTS payments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    client_id INT NOT NULL,
    license_id INT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    payment_type ENUM('manual', 'gateway') DEFAULT 'manual',
    payment_status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    transaction_id VARCHAR(200),
    payment_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    notes TEXT,
    recorded_by INT,
    FOREIGN KEY (client_id) REFERENCES clients(id),
    FOREIGN KEY (license_id) REFERENCES license_keys(id)
);

-- AMS Plans
INSERT INTO plans (product_type, plan_name, duration_months, price) VALUES 
('AMS', '1 Month', 1, 299.00),
('AMS', '3 Months', 3, 750.00),
('AMS', '6 Months', 6, 1500.00),
('AMS', '1 Year', 12, 2400.00);

-- CMS Plans
INSERT INTO plans (product_type, plan_name, duration_months, price) VALUES 
('CMS', '1 Month', 1, 1199.00),
('CMS', '6 Months', 6, 6900.00),
('CMS', '1 Year', 12, 12000.00);
