<?php
$step = $_GET['step'] ?? 1;
$error = null;
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['install'])) {
    $host = $_POST['host'];
    $name = $_POST['name'];
    $user = $_POST['user'];
    $pass = $_POST['pass'];
    
    try {
        $pdo = new PDO("mysql:host=$host;charset=utf8mb4", $user, $pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET utf8mb4 COLLATE utf8mb4_persian_ci");
        $pdo->exec("USE `$name`");
        
        $config_content = "<?php\n\n\$db_host = '$host';\n\$db_name = '$name';\n\$db_user = '$user';\n\$db_pass = '$pass';\n\ntry {\n    \$pdo = new PDO(\"mysql:host=\$db_host;dbname=\$db_name;charset=utf8mb4\", \$db_user, \$db_pass, [\n        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n        PDO::MYSQL_ATTR_INIT_COMMAND => \"SET NAMES utf8mb4 COLLATE utf8mb4_persian_ci\"\n    ]);\n} catch(PDOException \$e) {\n    die(\"خطا: \" . \$e->getMessage());\n}\n\nif (!function_exists('displayText')) {\n    function displayText(\$text) {\n        if (\$text === null) return '';\n        return htmlspecialchars(\$text, ENT_QUOTES, 'UTF-8');\n    }\n}\n?>";
        
        file_put_contents('config.php', $config_content);
        
        require_once 'config.php';
        
        $tables = [
            'admin' => "CREATE TABLE IF NOT EXISTS `admin` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `username` varchar(50) NOT NULL UNIQUE,
                `password` varchar(255) NOT NULL,
                `full_name` varchar(100) DEFAULT NULL,
                `last_login` datetime DEFAULT NULL,
                `last_ip` varchar(45) DEFAULT NULL,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'agents' => "CREATE TABLE IF NOT EXISTS `agents` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `name` varchar(100) NOT NULL,
                `token` varchar(100) NOT NULL UNIQUE,
                `balance` bigint DEFAULT 0,
                `discount` int NOT NULL DEFAULT 0,
                `service_limit` int NOT NULL DEFAULT 0,
                `status` tinyint(1) NOT NULL DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'panels' => "CREATE TABLE IF NOT EXISTS `panels` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `name` varchar(100) NOT NULL,
                `url` varchar(255) NOT NULL,
                `username` varchar(100) DEFAULT NULL,
                `password` varchar(255) DEFAULT NULL,
                `api_token` text DEFAULT NULL,
                `version` enum('old','new') NOT NULL DEFAULT 'old',
                `sub_domain` varchar(100) DEFAULT NULL,
                `sub_port` int NOT NULL DEFAULT 443,
                `sub_path` varchar(100) NOT NULL DEFAULT 'sub',
                `inbound_id` int NOT NULL DEFAULT 1,
                `extra_traffic_enabled` tinyint(1) NOT NULL DEFAULT 0,
                `extra_traffic_price_per_gb` decimal(10,0) NOT NULL DEFAULT 0,
                `extra_traffic_min` decimal(10,2) NOT NULL DEFAULT 0.00,
                `extra_traffic_max` decimal(10,2) NOT NULL DEFAULT 0.00,
                `bulk_purchase_enabled` tinyint(1) DEFAULT 0,
                `bulk_min_quantity` int DEFAULT 1,
                `bulk_max_quantity` int DEFAULT 10,
                `status` tinyint(1) NOT NULL DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'plans' => "CREATE TABLE IF NOT EXISTS `plans` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `name` varchar(100) NOT NULL,
                `panel_id` int NOT NULL,
                `volume_gb` decimal(10,3) DEFAULT 0.000,
                `days` int NOT NULL DEFAULT 0,
                `price` bigint NOT NULL,
                `status` tinyint(1) NOT NULL DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (`panel_id`) REFERENCES `panels`(`id`) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'agent_servers' => "CREATE TABLE IF NOT EXISTS `agent_servers` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `agent_id` int NOT NULL,
                `panel_id` int NOT NULL,
                `plan_id` int DEFAULT NULL,
                `username` varchar(100) NOT NULL,
                `uuid` varchar(100) DEFAULT NULL,
                `sub_id` varchar(100) DEFAULT NULL,
                `sub_link` text DEFAULT NULL,
                `volume_gb` decimal(10,3) DEFAULT 0.000,
                `days` int NOT NULL DEFAULT 0,
                `price` bigint NOT NULL,
                `expiry_date` datetime DEFAULT NULL,
                `status` tinyint(1) NOT NULL DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (`agent_id`) REFERENCES `agents`(`id`) ON DELETE CASCADE,
                FOREIGN KEY (`panel_id`) REFERENCES `panels`(`id`) ON DELETE CASCADE,
                FOREIGN KEY (`plan_id`) REFERENCES `plans`(`id`) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'balance_requests' => "CREATE TABLE IF NOT EXISTS `balance_requests` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `agent_id` int NOT NULL,
                `agent_name` varchar(255) NOT NULL,
                `agent_token` varchar(255) NOT NULL,
                `amount` decimal(15,0) NOT NULL,
                `selected_bank_account_id` int DEFAULT NULL,
                `selected_bank_details` text DEFAULT NULL,
                `receipt_image` varchar(500) DEFAULT NULL,
                `receipt_text` text DEFAULT NULL,
                `receipt_tracking_code` varchar(100) DEFAULT NULL,
                `receipt_deposit_time` varchar(50) DEFAULT NULL,
                `request_tracking_code` varchar(50) NOT NULL UNIQUE,
                `status` enum('pending','approved','rejected') DEFAULT 'pending',
                `admin_note` text DEFAULT NULL,
                `user_note` text DEFAULT NULL,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `processed_at` timestamp NULL DEFAULT NULL,
                KEY `agent_id` (`agent_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'extra_traffic_logs' => "CREATE TABLE IF NOT EXISTS `extra_traffic_logs` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `server_id` int NOT NULL,
                `agent_id` int NOT NULL,
                `panel_id` int NOT NULL,
                `username` varchar(255) NOT NULL,
                `volume_gb` decimal(10,3) NOT NULL,
                `price` decimal(15,0) NOT NULL,
                `discount_percent` int DEFAULT 0,
                `original_price` bigint DEFAULT 0,
                `old_volume_gb` decimal(10,3) NOT NULL,
                `new_volume_gb` decimal(10,3) NOT NULL,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'payment_accounts' => "CREATE TABLE IF NOT EXISTS `payment_accounts` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `bank_name` varchar(100) NOT NULL,
                `card_number` varchar(20) NOT NULL,
                `card_owner` varchar(255) NOT NULL,
                `shaba_number` varchar(30) DEFAULT NULL,
                `description` text DEFAULT NULL,
                `qr_code` varchar(500) DEFAULT NULL,
                `is_active` tinyint(1) DEFAULT 1,
                `sort_order` int DEFAULT 0,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `updated_at` timestamp NULL DEFAULT NULL,
                KEY `is_active` (`is_active`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'announcements' => "CREATE TABLE IF NOT EXISTS `announcements` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `title` varchar(200) NOT NULL,
                `preview` text NOT NULL,
                `content` longtext NOT NULL,
                `status` tinyint(1) NOT NULL DEFAULT 1,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'tickets' => "CREATE TABLE IF NOT EXISTS `tickets` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `ticket_number` varchar(50) NOT NULL UNIQUE,
                `agent_id` int NOT NULL,
                `agent_name` varchar(255) NOT NULL,
                `agent_token` varchar(255) NOT NULL,
                `subject` varchar(255) NOT NULL,
                `department` enum('technical','financial') NOT NULL DEFAULT 'technical',
                `priority` enum('normal','high') NOT NULL DEFAULT 'normal',
                `message` text NOT NULL,
                `admin_reply` text DEFAULT NULL,
                `admin_reply_at` timestamp NULL DEFAULT NULL,
                `status` enum('pending','answered','closed') NOT NULL DEFAULT 'pending',
                `closed_by` enum('agent','admin') DEFAULT NULL,
                `closed_at` timestamp NULL DEFAULT NULL,
                `system_active` tinyint(1) NOT NULL DEFAULT 1,
                `ticket_limit` int NOT NULL DEFAULT 10,
                `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `updated_at` timestamp NULL DEFAULT NULL,
                KEY `agent_id` (`agent_id`),
                KEY `status` (`status`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci",
            
            'settings' => "CREATE TABLE IF NOT EXISTS `settings` (
                `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
                `setting_key` varchar(100) NOT NULL UNIQUE,
                `setting_value` text DEFAULT NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_persian_ci"
        ];
        
        foreach ($tables as $table => $sql) {
            $pdo->exec($sql);
        }
        
        $columns_to_add = [
            'panels' => [
                'bulk_purchase_enabled' => "ALTER TABLE `panels` ADD COLUMN IF NOT EXISTS `bulk_purchase_enabled` tinyint(1) DEFAULT 0",
                'bulk_min_quantity' => "ALTER TABLE `panels` ADD COLUMN IF NOT EXISTS `bulk_min_quantity` int DEFAULT 1",
                'bulk_max_quantity' => "ALTER TABLE `panels` ADD COLUMN IF NOT EXISTS `bulk_max_quantity` int DEFAULT 10"
            ],
            'extra_traffic_logs' => [
                'discount_percent' => "ALTER TABLE `extra_traffic_logs` ADD COLUMN IF NOT EXISTS `discount_percent` int DEFAULT 0",
                'original_price' => "ALTER TABLE `extra_traffic_logs` ADD COLUMN IF NOT EXISTS `original_price` bigint DEFAULT 0"
            ]
        ];
        
        foreach ($columns_to_add as $table => $columns) {
            foreach ($columns as $column => $sql) {
                try {
                    $pdo->exec($sql);
                } catch (PDOException $e) {
                    if (strpos($e->getMessage(), 'Duplicate column') === false) {
                        throw $e;
                    }
                }
            }
        }
        
        $stmt = $pdo->query("SELECT COUNT(*) FROM admin");
        if ($stmt->fetchColumn() == 0) {
            $hashed = password_hash('admin123', PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO admin (username, password, full_name) VALUES ('admin', ?, 'مدیر سیستم')")->execute([$hashed]);
        }
        
        unlink(__FILE__);
        header("Location: index.php?install=success");
        exit;
        
    } catch (PDOException $e) {
        $error = "خطا: " . $e->getMessage();
    }
}

if ($step == 1 && !$error && !$success):
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <title>نصب سیستم</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Tahoma', system-ui, -apple-system, sans-serif;
            padding: 20px;
        }
        .install-container {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(12px);
            border-radius: 32px;
            padding: 32px;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
            border: 1px solid rgba(255,255,255,0.2);
        }
        h2 {
            color: white;
            text-align: center;
            margin-bottom: 24px;
            font-size: 28px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            color: rgba(255,255,255,0.9);
            margin-bottom: 8px;
            font-size: 14px;
        }
        input {
            width: 100%;
            padding: 12px 16px;
            border: none;
            border-radius: 16px;
            background: rgba(255,255,255,0.15);
            color: white;
            font-size: 14px;
            transition: all 0.3s;
        }
        input:focus {
            outline: none;
            background: rgba(255,255,255,0.25);
            box-shadow: 0 0 0 3px rgba(139,92,246,0.5);
        }
        button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #8b5cf6, #6d28d9);
            border: none;
            border-radius: 20px;
            color: white;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }
        button:hover {
            transform: translateY(-2px);
        }
        .error {
            background: rgba(244,63,94,0.2);
            border: 1px solid #f43f5e;
            padding: 12px;
            border-radius: 16px;
            color: #fda4af;
            margin-bottom: 20px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <h2>🚀 نصب سیستم</h2>
        <?php if($error): ?>
            <div class="error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="form-group">
                <label>📡 هاست دیتابیس</label>
                <input type="text" name="host" value="localhost" required>
            </div>
            <div class="form-group">
                <label>💾 نام دیتابیس</label>
                <input type="text" name="name" required>
            </div>
            <div class="form-group">
                <label>👤 نام کاربری دیتابیس</label>
                <input type="text" name="user" required>
            </div>
            <div class="form-group">
                <label>🔑 رمز عبور دیتابیس</label>
                <input type="password" name="pass">
            </div>
            <button type="submit" name="install">نصب و راه‌اندازی</button>
        </form>
    </div>
</body>
</html>
<?php endif; ?>