<?php
/**
 * PAKClub Admin Panel - Installation Script
 * Visit this file once to set up the database tables
 */

// Show all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Prevent re-installation if lock file exists
$lockFile = __DIR__ . '/.installed.lock';

$dbHost = 'localhost';
$dbName = 'luckrgur_HACK';
$dbUser = 'luckrgur_HACK';
$dbPass = 'luckrgur_HACK';

$results = [];
$errors = [];
$success = true;

try {
    $pdo = new PDO(
        "mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4",
        $dbUser,
        $dbPass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
    $results[] = "✅ Database connection successful";
} catch (PDOException $e) {
    $errors[] = "❌ Database connection failed: " . $e->getMessage();
    $success = false;
    $pdo = null;
}

if ($pdo) {
    // ── Table: apps ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `apps` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `pkg_name` VARCHAR(255) NOT NULL UNIQUE,
                `app_name` VARCHAR(255) NOT NULL,
                `app_domain` VARCHAR(255) DEFAULT NULL,
                `whatsapp_link` TEXT DEFAULT NULL,
                `refer_link` VARCHAR(500) DEFAULT NULL,
                `app_logo` VARCHAR(500) DEFAULT NULL,
                `app_version` VARCHAR(50) DEFAULT '1.0.0',
                `app_status` ENUM('active', 'inactive', 'maintenance') DEFAULT 'active',
                `min_version` VARCHAR(50) DEFAULT '1.0.0',
                `force_update` TINYINT(1) DEFAULT 0,
                `update_url` TEXT DEFAULT NULL,
                `app_description` TEXT DEFAULT NULL,
                `notification_title` VARCHAR(255) DEFAULT NULL,
                `notification_body` TEXT DEFAULT NULL,
                `notification_image` VARCHAR(500) DEFAULT NULL,
                `notification_url` TEXT DEFAULT NULL,
                `popup_enabled` TINYINT(1) DEFAULT 0,
                `popup_title` VARCHAR(255) DEFAULT NULL,
                `popup_message` TEXT DEFAULT NULL,
                `popup_button_text` VARCHAR(100) DEFAULT 'OK',
                `popup_button_url` TEXT DEFAULT NULL,
                `popup_image` VARCHAR(500) DEFAULT NULL,
                `interstitial_ad_id` VARCHAR(255) DEFAULT NULL,
                `banner_ad_id` VARCHAR(255) DEFAULT NULL,
                `rewarded_ad_id` VARCHAR(255) DEFAULT NULL,
                `native_ad_id` VARCHAR(255) DEFAULT NULL,
                `ad_network` ENUM('admob', 'facebook', 'unity', 'applovin', 'none') DEFAULT 'none',
                `ads_enabled` TINYINT(1) DEFAULT 0,
                `custom_data` JSON DEFAULT NULL,
                `api_calls` INT DEFAULT 0,
                `last_api_call` DATETIME DEFAULT NULL,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX `idx_pkg_name` (`pkg_name`),
                INDEX `idx_app_status` (`app_status`),
                INDEX `idx_created_at` (`created_at`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'apps' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'apps' table: " . $e->getMessage();
        $success = false;
    }

    // ── Table: settings ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `settings` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `setting_key` VARCHAR(255) NOT NULL UNIQUE,
                `setting_value` TEXT DEFAULT NULL,
                `setting_type` ENUM('text', 'number', 'boolean', 'json', 'url') DEFAULT 'text',
                `description` VARCHAR(500) DEFAULT NULL,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX `idx_setting_key` (`setting_key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'settings' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'settings' table: " . $e->getMessage();
        $success = false;
    }

    // ── Table: admin_logs ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `admin_logs` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `action` VARCHAR(100) NOT NULL,
                `details` TEXT DEFAULT NULL,
                `ip_address` VARCHAR(45) DEFAULT NULL,
                `user_agent` TEXT DEFAULT NULL,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX `idx_action` (`action`),
                INDEX `idx_created_at` (`created_at`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'admin_logs' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'admin_logs' table: " . $e->getMessage();
        $success = false;
    }

    // ── Table: api_keys ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `api_keys` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `key_name` VARCHAR(255) NOT NULL,
                `api_key` VARCHAR(255) NOT NULL UNIQUE,
                `is_active` TINYINT(1) DEFAULT 1,
                `rate_limit` INT DEFAULT 100,
                `total_requests` INT DEFAULT 0,
                `last_used` DATETIME DEFAULT NULL,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX `idx_api_key` (`api_key`),
                INDEX `idx_is_active` (`is_active`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'api_keys' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'api_keys' table: " . $e->getMessage();
        $success = false;
    }

    // ── Table: blocked_devices ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `blocked_devices` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `device_id` VARCHAR(255) NOT NULL UNIQUE,
                `device_info` TEXT DEFAULT NULL,
                `reason` VARCHAR(500) DEFAULT NULL,
                `blocked_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                INDEX `idx_device_id` (`device_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'blocked_devices' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'blocked_devices' table: " . $e->getMessage();
        $success = false;
    }

    // ── Table: audios ──
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `audios` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `class_name` VARCHAR(255) NOT NULL,
                `audio_title` VARCHAR(255) DEFAULT NULL,
                `audio_file` VARCHAR(500) NOT NULL,
                `app_id` INT DEFAULT NULL,
                `is_active` TINYINT(1) DEFAULT 1,
                `play_count` INT DEFAULT 0,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX `idx_class_name` (`class_name`),
                INDEX `idx_app_id` (`app_id`),
                INDEX `idx_is_active` (`is_active`),
                FOREIGN KEY (`app_id`) REFERENCES `apps`(`id`) ON DELETE SET NULL
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        $results[] = "✅ Table 'audios' created successfully";
    } catch (PDOException $e) {
        $errors[] = "❌ Error creating 'audios' table: " . $e->getMessage();
        $success = false;
    }

    // ── Insert default settings ──
    try {
        $defaultSettings = [
            ['main_domain', '', 'url', 'Main domain for building refer links (e.g. pakclub24.club)'],
            ['api_rate_limit', '100', 'number', 'Max API requests per minute per IP'],
            ['maintenance_mode', '0', 'boolean', 'Enable/disable maintenance mode globally'],
            ['maintenance_message', 'We are currently performing maintenance. Please try again later.', 'text', 'Message shown during maintenance'],
            ['telegram_bot_token', '', 'text', 'Telegram bot token for notifications'],
            ['telegram_chat_id', '', 'text', 'Telegram chat ID for notifications'],
            ['whatsapp_support', '', 'url', 'Global WhatsApp support link'],
            ['default_refer_link', '', 'text', 'Default refer link path for new apps'],
            ['logo_quality', '85', 'number', 'JPEG quality for uploaded logos (1-100)'],
            ['max_upload_size', '5', 'number', 'Maximum upload size in MB'],
            ['cors_origins', '*', 'text', 'Allowed CORS origins (comma separated or *)'],
            ['api_response_cache', '300', 'number', 'API response cache time in seconds'],
        ];

        $stmt = $pdo->prepare("INSERT IGNORE INTO `settings` (`setting_key`, `setting_value`, `setting_type`, `description`) VALUES (?, ?, ?, ?)");
        foreach ($defaultSettings as $setting) {
            $stmt->execute($setting);
        }
        $results[] = "✅ Default settings inserted";
    } catch (PDOException $e) {
        $errors[] = "❌ Error inserting default settings: " . $e->getMessage();
        $success = false;
    }

    // ── Generate default API key ──
    try {
        $defaultKey = bin2hex(random_bytes(32));
        $stmt = $pdo->prepare("INSERT IGNORE INTO `api_keys` (`key_name`, `api_key`) VALUES ('Default Key', ?)");
        $stmt->execute([$defaultKey]);
        $results[] = "✅ Default API key generated: <code>{$defaultKey}</code>";
    } catch (PDOException $e) {
        $errors[] = "❌ Error generating API key: " . $e->getMessage();
        $success = false;
    }

    // ── Create uploads directory ──
    $uploadDir = __DIR__ . '/uploads/logos/';
    if (!is_dir($uploadDir)) {
        if (mkdir($uploadDir, 0755, true)) {
            $results[] = "✅ Logo upload directory created";
        } else {
            $errors[] = "❌ Failed to create logo upload directory";
            $success = false;
        }
    } else {
        $results[] = "✅ Logo upload directory already exists";
    }

    $audioDir = __DIR__ . '/uploads/audios/';
    if (!is_dir($audioDir)) {
        if (mkdir($audioDir, 0755, true)) {
            $results[] = "✅ Audio upload directory created";
        } else {
            $errors[] = "❌ Failed to create audio upload directory";
            $success = false;
        }
    } else {
        $results[] = "✅ Audio upload directory already exists";
    }

    // ── Create .htaccess for uploads ──
    $htaccess = $uploadDir . '.htaccess';
    if (!file_exists($htaccess)) {
        file_put_contents($htaccess, "Options -Indexes\n<FilesMatch \"\\.(php|php5|phtml)$\">\n    Deny from all\n</FilesMatch>");
        $results[] = "✅ Upload security .htaccess created";
    }

    // ── Create lock file on success ──
    if ($success) {
        file_put_contents($lockFile, date('Y-m-d H:i:s'));
    }

    // ── Log installation ──
    try {
        $stmt = $pdo->prepare("INSERT INTO `admin_logs` (`action`, `details`, `ip_address`, `user_agent`) VALUES ('install', 'Installation completed', ?, ?)");
        $stmt->execute([$_SERVER['REMOTE_ADDR'] ?? '127.0.0.1', $_SERVER['HTTP_USER_AGENT'] ?? 'CLI']);
    } catch (Exception $e) {
        // Silently fail
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PAKClub Admin - Installation</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', sans-serif;
            background: #0a0a0f;
            color: #e0e0e0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            background-image: 
                radial-gradient(ellipse at 20% 50%, rgba(255, 165, 0, 0.08) 0%, transparent 50%),
                radial-gradient(ellipse at 80% 20%, rgba(255, 69, 0, 0.06) 0%, transparent 50%);
        }
        .installer-card {
            background: linear-gradient(145deg, #13131a, #1a1a25);
            border: 1px solid rgba(255, 165, 0, 0.15);
            border-radius: 20px;
            padding: 40px;
            max-width: 600px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5), 0 0 40px rgba(255, 165, 0, 0.05);
        }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo h1 {
            font-size: 28px;
            font-weight: 800;
            background: linear-gradient(135deg, #FFA500, #FF6B00);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .logo p { color: #888; font-size: 14px; margin-top: 5px; }
        .status-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.03);
            border-radius: 10px;
            margin-bottom: 8px;
            font-size: 14px;
            border: 1px solid rgba(255, 255, 255, 0.05);
            transition: all 0.3s ease;
        }
        .status-item:hover { background: rgba(255, 255, 255, 0.05); }
        .status-item.success { border-left: 3px solid #00c853; }
        .status-item.error { border-left: 3px solid #ff1744; }
        .final-status {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
            border-radius: 15px;
        }
        .final-status.success-bg {
            background: linear-gradient(135deg, rgba(0, 200, 83, 0.1), rgba(0, 200, 83, 0.05));
            border: 1px solid rgba(0, 200, 83, 0.2);
        }
        .final-status.error-bg {
            background: linear-gradient(135deg, rgba(255, 23, 68, 0.1), rgba(255, 23, 68, 0.05));
            border: 1px solid rgba(255, 23, 68, 0.2);
        }
        .final-status h2 { font-size: 20px; margin-bottom: 10px; }
        .final-status a {
            display: inline-block;
            margin-top: 15px;
            padding: 12px 30px;
            background: linear-gradient(135deg, #FFA500, #FF6B00);
            color: #fff;
            text-decoration: none;
            border-radius: 10px;
            font-weight: 600;
            transition: transform 0.2s;
        }
        .final-status a:hover { transform: translateY(-2px); }
        code {
            background: rgba(255, 165, 0, 0.1);
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: #FFA500;
            word-break: break-all;
        }
        .warning-box {
            background: rgba(255, 165, 0, 0.08);
            border: 1px solid rgba(255, 165, 0, 0.2);
            border-radius: 10px;
            padding: 15px;
            margin-top: 20px;
            font-size: 13px;
            color: #FFA500;
        }
    </style>
</head>
<body>
    <div class="installer-card">
        <div class="logo">
            <h1>⚡ PAKClub Admin</h1>
            <p>Installation Wizard v2.0.0</p>
        </div>

        <?php foreach ($results as $r): ?>
            <div class="status-item success"><?= $r ?></div>
        <?php endforeach; ?>

        <?php foreach ($errors as $e): ?>
            <div class="status-item error"><?= $e ?></div>
        <?php endforeach; ?>

        <?php if ($success): ?>
            <div class="final-status success-bg">
                <h2>🎉 Installation Complete!</h2>
                <p>All tables and settings have been configured successfully.</p>
                <a href="ir-admin/">→ Open Admin Panel</a>
            </div>
            <div class="warning-box">
                ⚠️ <strong>Security:</strong> Delete this <code>install.php</code> file after installation for security.
            </div>
        <?php else: ?>
            <div class="final-status error-bg">
                <h2>⚠️ Installation Failed</h2>
                <p>Some errors occurred. Please fix them and try again.</p>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
