<?php
/**
 * TrackPro Installation Script
 * Run once to set up the database and admin account
 * DELETE THIS FILE AFTER INSTALLATION
 */

// ─── Configuration ───────────────────────────────────────────────────────────
$config = [
    'db_host'     => 'localhost',
    'db_name'     => 'trackpro_db',
    'db_user'     => 'your_db_user',
    'db_pass'     => 'your_db_password',
    'admin_user'  => 'admin',
    'admin_pass'  => 'ChangeMe!2026',
    'admin_email' => 'admin@yourdomain.com',
];

// ─── Run Installation ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $config['db_host']    = trim($_POST['db_host'] ?? $config['db_host']);
    $config['db_name']    = trim($_POST['db_name'] ?? $config['db_name']);
    $config['db_user']    = trim($_POST['db_user'] ?? $config['db_user']);
    $config['db_pass']    = $_POST['db_pass'] ?? $config['db_pass'];
    $config['admin_user'] = trim($_POST['admin_user'] ?? $config['admin_user']);
    $config['admin_pass'] = $_POST['admin_pass'] ?? $config['admin_pass'];
    $config['admin_email']= trim($_POST['admin_email'] ?? $config['admin_email']);

    $errors = [];

    try {
        $pdo = new PDO(
            "mysql:host={$config['db_host']}",
            $config['db_user'],
            $config['db_pass'],
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );

        // Create database
        $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$config['db_name']}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        $pdo->exec("USE `{$config['db_name']}`");

        // ─── Users table ─────────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `users` (
            `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `username` VARCHAR(64) NOT NULL UNIQUE,
            `email` VARCHAR(255) NOT NULL UNIQUE,
            `password_hash` VARCHAR(255) NOT NULL,
            `role` ENUM('superadmin','admin','analyst','viewer') NOT NULL DEFAULT 'viewer',
            `is_active` TINYINT(1) NOT NULL DEFAULT 1,
            `last_login` DATETIME NULL,
            `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX `idx_role` (`role`),
            INDEX `idx_active` (`is_active`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Tracking links table ────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `tracking_links` (
            `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `link_uid` VARCHAR(32) NOT NULL UNIQUE,
            `title` VARCHAR(255) NOT NULL,
            `description` TEXT NULL,
            `destination_url` VARCHAR(2048) NULL,
            `landing_mode` ENUM('redirect','neutral','custom') NOT NULL DEFAULT 'neutral',
            `custom_html` TEXT NULL,
            `is_active` TINYINT(1) NOT NULL DEFAULT 1,
            `expires_at` DATETIME NULL,
            `max_hits` INT UNSIGNED NULL,
            `hit_count` INT UNSIGNED NOT NULL DEFAULT 0,
            `created_by` INT UNSIGNED NOT NULL,
            `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX `idx_uid` (`link_uid`),
            INDEX `idx_active` (`is_active`),
            INDEX `idx_created_by` (`created_by`),
            FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Sessions table ──────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `sessions` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_uid` VARCHAR(64) NOT NULL UNIQUE,
            `link_id` INT UNSIGNED NOT NULL,
            `visitor_hash` VARCHAR(64) NULL,
            `started_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `last_activity` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            `duration_seconds` INT UNSIGNED NOT NULL DEFAULT 0,
            `page_views` INT UNSIGNED NOT NULL DEFAULT 1,
            `is_bot` TINYINT(1) NOT NULL DEFAULT 0,
            INDEX `idx_link` (`link_id`),
            INDEX `idx_started` (`started_at`),
            INDEX `idx_visitor` (`visitor_hash`),
            FOREIGN KEY (`link_id`) REFERENCES `tracking_links`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Network & IP data ───────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `network_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `ip_address` VARCHAR(45) NOT NULL,
            `ip_version` TINYINT NOT NULL DEFAULT 4,
            `isp` VARCHAR(255) NULL,
            `mobile_carrier` VARCHAR(255) NULL,
            `asn` VARCHAR(32) NULL,
            `as_org` VARCHAR(255) NULL,
            `network_type` ENUM('residential','mobile','datacenter','business','education','unknown') DEFAULT 'unknown',
            `is_proxy` TINYINT(1) NOT NULL DEFAULT 0,
            `is_vpn` TINYINT(1) NOT NULL DEFAULT 0,
            `is_tor` TINYINT(1) NOT NULL DEFAULT 0,
            `abuse_score` TINYINT UNSIGNED NULL,
            `reputation_score` TINYINT UNSIGNED NULL,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            INDEX `idx_ip` (`ip_address`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Location data ───────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `location_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `country` VARCHAR(100) NULL,
            `country_code` CHAR(2) NULL,
            `region` VARCHAR(128) NULL,
            `city` VARCHAR(128) NULL,
            `postal_code` VARCHAR(20) NULL,
            `latitude` DECIMAL(10,7) NULL,
            `longitude` DECIMAL(10,7) NULL,
            `timezone` VARCHAR(64) NULL,
            `language` VARCHAR(32) NULL,
            `locale` VARCHAR(16) NULL,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            INDEX `idx_country` (`country_code`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Device & hardware data ──────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `device_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `device_type` ENUM('desktop','mobile','tablet','tv','console','wearable','unknown') DEFAULT 'unknown',
            `os_name` VARCHAR(64) NULL,
            `os_version` VARCHAR(32) NULL,
            `cpu_arch` VARCHAR(32) NULL,
            `gpu_vendor` VARCHAR(128) NULL,
            `gpu_renderer` VARCHAR(255) NULL,
            `screen_width` SMALLINT UNSIGNED NULL,
            `screen_height` SMALLINT UNSIGNED NULL,
            `viewport_width` SMALLINT UNSIGNED NULL,
            `viewport_height` SMALLINT UNSIGNED NULL,
            `color_depth` TINYINT UNSIGNED NULL,
            `pixel_ratio` DECIMAL(4,2) NULL,
            `touch_support` TINYINT(1) NULL,
            `max_touch_points` TINYINT UNSIGNED NULL,
            `battery_level` DECIMAL(5,2) NULL,
            `battery_charging` TINYINT(1) NULL,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Browser & client data ───────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `browser_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `browser_name` VARCHAR(64) NULL,
            `browser_version` VARCHAR(32) NULL,
            `browser_engine` VARCHAR(64) NULL,
            `user_agent` TEXT NULL,
            `accept_types` TEXT NULL,
            `accept_language` VARCHAR(255) NULL,
            `accept_encoding` VARCHAR(128) NULL,
            `dnt_flag` TINYINT(1) NULL,
            `cookies_enabled` TINYINT(1) NULL,
            `js_enabled` TINYINT(1) NOT NULL DEFAULT 1,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Fingerprint data ────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `fingerprint_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `canvas_hash` VARCHAR(64) NULL,
            `webgl_hash` VARCHAR(64) NULL,
            `audio_hash` VARCHAR(64) NULL,
            `font_list` TEXT NULL,
            `font_hash` VARCHAR(64) NULL,
            `plugin_list` TEXT NULL,
            `plugin_hash` VARCHAR(64) NULL,
            `hardware_concurrency` TINYINT UNSIGNED NULL,
            `device_memory` DECIMAL(5,2) NULL,
            `combined_fingerprint` VARCHAR(128) NULL,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            INDEX `idx_fingerprint` (`combined_fingerprint`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Behavioral analytics ────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `behavioral_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `event_type` ENUM('pageview','click','scroll','mouse','keystroke','navigation') NOT NULL,
            `event_data` JSON NULL,
            `timestamp` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
            INDEX `idx_session` (`session_id`),
            INDEX `idx_type` (`event_type`),
            INDEX `idx_time` (`timestamp`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Attribution data ────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `attribution_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `referrer_url` TEXT NULL,
            `referrer_domain` VARCHAR(255) NULL,
            `utm_source` VARCHAR(255) NULL,
            `utm_medium` VARCHAR(255) NULL,
            `utm_campaign` VARCHAR(255) NULL,
            `utm_term` VARCHAR(255) NULL,
            `utm_content` VARCHAR(255) NULL,
            `campaign_id` VARCHAR(128) NULL,
            `collected_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Risk & fraud scores ─────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `risk_data` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `device_trust_score` DECIMAL(5,2) NULL,
            `fraud_score` DECIMAL(5,2) NULL,
            `risk_score` DECIMAL(5,2) NULL,
            `bot_likelihood` DECIMAL(5,2) NULL,
            `is_emulator` TINYINT(1) NULL,
            `is_rooted` TINYINT(1) NULL,
            `risk_factors` JSON NULL,
            `calculated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            INDEX `idx_risk` (`risk_score`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Consent & compliance log ────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `consent_log` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `session_id` BIGINT UNSIGNED NOT NULL,
            `consent_type` VARCHAR(64) NOT NULL,
            `consent_given` TINYINT(1) NOT NULL DEFAULT 0,
            `ip_address` VARCHAR(45) NULL,
            `user_agent` TEXT NULL,
            `recorded_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_session` (`session_id`),
            FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Audit log ───────────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `audit_log` (
            `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `user_id` INT UNSIGNED NULL,
            `action` VARCHAR(128) NOT NULL,
            `entity_type` VARCHAR(64) NULL,
            `entity_id` VARCHAR(64) NULL,
            `details` JSON NULL,
            `ip_address` VARCHAR(45) NULL,
            `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_user` (`user_id`),
            INDEX `idx_action` (`action`),
            INDEX `idx_created` (`created_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // ─── Settings table ──────────────────────────────────────────────
        $pdo->exec("CREATE TABLE IF NOT EXISTS `settings` (
            `key_name` VARCHAR(128) PRIMARY KEY,
            `value` TEXT NULL,
            `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        // Insert default settings
        $pdo->exec("INSERT IGNORE INTO `settings` (`key_name`, `value`) VALUES
            ('site_name', 'TrackPro'),
            ('data_retention_days', '365'),
            ('require_consent', '1'),
            ('default_landing_mode', 'neutral'),
            ('ip_lookup_api_key', ''),
            ('ip_lookup_provider', 'ip-api'),
            ('session_timeout_minutes', '30'),
            ('max_export_rows', '50000'),
            ('enable_behavioral', '1'),
            ('enable_fingerprinting', '1')
        ");

        // Create admin user
        $hash = password_hash($config['admin_pass'], PASSWORD_BCRYPT, ['cost' => 12]);
        $stmt = $pdo->prepare("INSERT IGNORE INTO `users` (`username`, `email`, `password_hash`, `role`) VALUES (?, ?, ?, 'superadmin')");
        $stmt->execute([$config['admin_user'], $config['admin_email'], $hash]);

        // Write config file
        $configContent = "<?php\nreturn [\n";
        $configContent .= "    'db_host' => '{$config['db_host']}',\n";
        $configContent .= "    'db_name' => '{$config['db_name']}',\n";
        $configContent .= "    'db_user' => '{$config['db_user']}',\n";
        $configContent .= "    'db_pass' => '{$config['db_pass']}',\n";
        $configContent .= "    'app_key' => '" . bin2hex(random_bytes(32)) . "',\n";
        $configContent .= "    'base_url' => '" . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . "',\n";
        $configContent .= "];\n";

        file_put_contents(__DIR__ . '/includes/config.php', $configContent);

        $success = true;

    } catch (PDOException $e) {
        $errors[] = "Database error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrackPro — Installation</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Segoe UI', system-ui, sans-serif; background: #0a0e17; color: #c8d0e0; min-height: 100vh; display: flex; align-items: center; justify-content: center; }
        .container { max-width: 520px; width: 100%; padding: 2rem; }
        h1 { font-size: 1.6rem; color: #fff; margin-bottom: .5rem; }
        .sub { color: #6b7a99; margin-bottom: 2rem; font-size: .9rem; }
        label { display: block; font-size: .8rem; color: #8899b4; margin-bottom: .3rem; margin-top: 1rem; text-transform: uppercase; letter-spacing: .05em; }
        input { width: 100%; padding: .7rem 1rem; background: #141a2a; border: 1px solid #1e2a42; border-radius: 8px; color: #e0e6f0; font-size: .95rem; }
        input:focus { outline: none; border-color: #3b82f6; }
        .btn { margin-top: 2rem; width: 100%; padding: .9rem; background: linear-gradient(135deg, #3b82f6, #2563eb); color: #fff; border: none; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; }
        .btn:hover { background: linear-gradient(135deg, #2563eb, #1d4ed8); }
        .success { background: #0d2818; border: 1px solid #166534; padding: 1.5rem; border-radius: 10px; margin-top: 1rem; }
        .success h2 { color: #4ade80; font-size: 1.1rem; margin-bottom: .5rem; }
        .error { background: #2a0a0a; border: 1px solid #7f1d1d; padding: 1rem; border-radius: 8px; color: #fca5a5; margin-top: 1rem; }
        .warn { background: #2a1f0a; border: 1px solid #854d0e; padding: 1rem; border-radius: 8px; color: #fbbf24; margin-top: 1rem; font-size: .85rem; }
    </style>
</head>
<body>
<div class="container">
    <?php if (!empty($success)): ?>
        <div class="success">
            <h2>✓ Installation Complete</h2>
            <p>Database tables created and admin account configured.</p>
            <p style="margin-top:.5rem;color:#86efac;"><strong>Login:</strong> <?= htmlspecialchars($config['admin_user']) ?></p>
        </div>
        <div class="warn">⚠ Delete this file (install.php) immediately for security, then visit <a href="admin/" style="color:#fbbf24;">/admin/</a> to log in.</div>
    <?php else: ?>
        <h1>TrackPro Installation</h1>
        <p class="sub">Configure your database and admin account to get started.</p>

        <?php if (!empty($errors)): ?>
            <?php foreach ($errors as $err): ?>
                <div class="error"><?= htmlspecialchars($err) ?></div>
            <?php endforeach; ?>
        <?php endif; ?>

        <form method="POST">
            <label>Database Host</label>
            <input type="text" name="db_host" value="localhost" required>
            <label>Database Name</label>
            <input type="text" name="db_name" value="trackpro_db" required>
            <label>Database User</label>
            <input type="text" name="db_user" value="" required>
            <label>Database Password</label>
            <input type="password" name="db_pass" value="" required>
            <label>Admin Username</label>
            <input type="text" name="admin_user" value="admin" required>
            <label>Admin Email</label>
            <input type="email" name="admin_email" value="" required>
            <label>Admin Password</label>
            <input type="password" name="admin_pass" value="" required minlength="8">
            <button type="submit" class="btn">Install TrackPro</button>
        </form>
    <?php endif; ?>
</div>
</body>
</html>
