<?php
// Run this to add CRM, Dealer, and Employee tables to the existing DB
define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PASS',''); define('DB_NAME','balimeen_steel');
try {
    $pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4", DB_USER, DB_PASS,
        [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    $pdo->exec("SET FOREIGN_KEY_CHECKS=0");

    // Dealers
    $pdo->exec("CREATE TABLE IF NOT EXISTS `dealers` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(150) NOT NULL,
        `company_name` VARCHAR(200) NOT NULL,
        `email` VARCHAR(200) NOT NULL UNIQUE,
        `phone` VARCHAR(20),
        `gstin` VARCHAR(30),
        `password` VARCHAR(255) NOT NULL,
        `address` TEXT,
        `city` VARCHAR(100),
        `state` VARCHAR(100),
        `pincode` VARCHAR(10),
        `status` ENUM('pending','approved','rejected','blocked') DEFAULT 'pending',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");

    // Employees
    $pdo->exec("CREATE TABLE IF NOT EXISTS `employees` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(150) NOT NULL,
        `email` VARCHAR(200) NOT NULL UNIQUE,
        `phone` VARCHAR(20),
        `role` ENUM('admin','sales_manager','support','logistics') DEFAULT 'sales_manager',
        `password` VARCHAR(255) NOT NULL,
        `status` ENUM('active','inactive') DEFAULT 'active',
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");

    // CRM Leads
    $pdo->exec("CREATE TABLE IF NOT EXISTS `crm_leads` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(150) NOT NULL,
        `company` VARCHAR(200),
        `email` VARCHAR(200),
        `phone` VARCHAR(20) NOT NULL,
        `source` VARCHAR(100) DEFAULT 'website',
        `status` ENUM('new','contacted','qualified','proposal_sent','converted','lost') DEFAULT 'new',
        `assigned_to` INT NULL,
        `notes` TEXT,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (`assigned_to`) REFERENCES `employees`(`id`) ON DELETE SET NULL
    ) ENGINE=InnoDB");

    $pdo->exec("SET FOREIGN_KEY_CHECKS=1");
    echo "<h2 style='color:green;font-family:sans-serif'>✅ CRM, Dealer, and Employee tables created!</h2>";
    echo "<a href='admin/index.php'>Go to Admin</a>";
} catch(PDOException $e) {
    echo "<h2 style='color:red'>Error: ".htmlspecialchars($e->getMessage())."</h2>";
}
