<?php
// setup.php - Smart Football Installation Script

// Security: Check if config already exists to prevent re-installation
if (file_exists('core/config.php')) {
    die("Application is already installed. To reinstall, please delete <code>core/config.php</code> and run this script again.");
}

$message = '';
$msg_type = '';
$step = isset($_REQUEST['step']) ? (int)$_REQUEST['step'] : 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step == 3) {
    // --- Process Installation ---
    $db_host = trim($_POST['db_host']);
    $db_name = trim($_POST['db_name']);
    $db_user = trim($_POST['db_user']);
    $db_pass = trim($_POST['db_pass']);
    $site_url = rtrim(trim($_POST['site_url']), '/');
    $app_name = trim($_POST['app_name']);
    $admin_user = trim($_POST['admin_user']);
    $admin_email = trim($_POST['admin_email']);
    $admin_pass = trim($_POST['admin_pass']);

    try {
        // 1. Test Database Connection
        $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            PDO::ATTR_EMULATE_PREPARES => false,
        ];
        $pdo = new PDO($dsn, $db_user, $db_pass, $options);

        // 2. Generate core/config.php
        $jwt_key = bin2hex(random_bytes(32));
        
        // Generate VAPID Keys for Push Notifications
        $vapid_public_key = '';
        $vapid_private_key = '';
        if (function_exists('openssl_pkey_new')) {
            $res = openssl_pkey_new([
                "digest_alg" => "sha256",
                "private_key_bits" => 4096,
                "private_key_type" => OPENSSL_KEYTYPE_EC,
                "curve_name" => "prime256v1"
            ]);
            if ($res) {
                $details = openssl_pkey_get_details($res);
                $vapid_public_key = rtrim(strtr(base64_encode("\x04" . $details['ec']['x'] . $details['ec']['y']), '+/', '-_'), '=');
                $vapid_private_key = rtrim(strtr(base64_encode($details['ec']['d']), '+/', '-_'), '=');
            }
        }

        $config_content = "<?php\n";
        $config_content .= "// Database Configuration\n";
        $config_content .= "define('DB_HOST', '$db_host');\n";
        $config_content .= "define('DB_USER', '$db_user');\n";
        $config_content .= "define('DB_PASS', '$db_pass');\n";
        $config_content .= "define('DB_NAME', '$db_name');\n\n";
        $config_content .= "// App Configuration\n";
        $config_content .= "define('URL_ROOT', '$site_url');\n";
        $config_content .= "define('APP_NAME', '$app_name');\n";
        $config_content .= "define('JWT_KEY', '$jwt_key');\n";
        $config_content .= "define('VAPID_PUBLIC_KEY', '$vapid_public_key');\n";
        $config_content .= "define('VAPID_PRIVATE_KEY', '$vapid_private_key');\n";
        $config_content .= "define('VAPID_SUBJECT', 'mailto:$admin_email');\n";
        $config_content .= "define('DEV_MODE', false); // Set to true for local development to show dev tools\n";
        
        if (!is_dir('core')) mkdir('core', 0755, true);
        if (file_put_contents('core/config.php', $config_content) === false) {
            throw new Exception("Could not write to core/config.php. Please check permissions.");
        }

        // 3. Create Database Tables
        $queries = [
            // Users
            "CREATE TABLE IF NOT EXISTS `users` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `first_name` varchar(50) NOT NULL,
              `last_name` varchar(50) NOT NULL,
              `username` varchar(50) NOT NULL,
              `email` varchar(100) NOT NULL,
              `phone_number` varchar(20) DEFAULT NULL,
              `password_hash` varchar(255) NOT NULL,
              `role` varchar(50) NOT NULL DEFAULT 'fan',
              `status` enum('active','banned') NOT NULL DEFAULT 'active',
              `ban_reason` text DEFAULT NULL,
              `profile_picture` varchar(255) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `username` (`username`),
              UNIQUE KEY `email` (`email`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Settings
            "CREATE TABLE IF NOT EXISTS `settings` (
              `setting_key` varchar(50) NOT NULL,
              `setting_value` text DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`setting_key`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Leagues
            "CREATE TABLE IF NOT EXISTS `leagues` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(255) NOT NULL,
              `country` varchar(100) DEFAULT NULL,
              `season` varchar(50) NOT NULL,
              `logo` varchar(255) DEFAULT NULL,
              `manager_id` int(11) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              `reg_fee_total` decimal(10,2) DEFAULT 0.00,
              `reg_deposit_pct` decimal(5,2) DEFAULT 50.00,
              `reg_inst2_pct` decimal(5,2) DEFAULT 30.00,
              `reg_inst2_games` int(11) DEFAULT 5,
              `reg_inst3_pct` decimal(5,2) DEFAULT 20.00,
              `reg_inst3_games` int(11) DEFAULT 10,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Clubs
            "CREATE TABLE IF NOT EXISTS `clubs` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(255) NOT NULL,
              `logo` varchar(255) DEFAULT NULL,
              `stadium` varchar(255) DEFAULT NULL,
              `league_id` int(11) DEFAULT NULL,
              `manager_id` int(11) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `name` (`name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Teams
            "CREATE TABLE IF NOT EXISTS `teams` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `club_id` int(11) NOT NULL,
              `name` varchar(255) NOT NULL,
              `manager_id` int(11) DEFAULT NULL,
              `roster_status` enum('draft','pending_approval','approved') NOT NULL DEFAULT 'draft',
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `club_id` (`club_id`,`name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Players
            "CREATE TABLE IF NOT EXISTS `players` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `team_id` int(11) DEFAULT NULL,
              `position` varchar(50) DEFAULT NULL,
              `squad_number` int(11) DEFAULT NULL,
              `fantasy_price` decimal(10,1) DEFAULT 5.0,
              `height_cm` int(11) DEFAULT NULL,
              `weight_kg` int(11) DEFAULT NULL,
              `preferred_foot` varchar(20) DEFAULT NULL,
              `date_of_birth` date DEFAULT NULL,
              `nationality` varchar(100) DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Fixtures
            "CREATE TABLE IF NOT EXISTS `fixtures` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `league_id` int(11) NOT NULL,
              `home_team_id` int(11) NOT NULL,
              `away_team_id` int(11) NOT NULL,
              `match_datetime` datetime NOT NULL,
              `gameweek` int(11) DEFAULT NULL,
              `venue` varchar(255) DEFAULT NULL,
              `status` enum('scheduled','live','postponed','cancelled','finished') DEFAULT 'scheduled',
              `first_half_start_time` datetime DEFAULT NULL,
              `first_half_end_time` datetime DEFAULT NULL,
              `second_half_start_time` datetime DEFAULT NULL,
              `second_half_end_time` datetime DEFAULT NULL,
              `home_team_score` int(11) DEFAULT 0,
              `away_team_score` int(11) DEFAULT 0,
              `commissioner_id` int(11) DEFAULT NULL,
              `referee_id` int(11) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              `home_team_paid_referee` tinyint(1) NOT NULL DEFAULT 0,
              `away_team_paid_referee` tinyint(1) NOT NULL DEFAULT 0,
              `referee_payment_status` enum('pending','paid') DEFAULT 'pending',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Wallets
            "CREATE TABLE IF NOT EXISTS `wallets` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `entity_type` enum('user','team','club','board') NOT NULL,
              `entity_id` int(11) NOT NULL,
              `balance` decimal(15,2) NOT NULL DEFAULT 0.00,
              `currency` varchar(3) NOT NULL DEFAULT 'USD',
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `entity_wallet` (`entity_type`,`entity_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Wallet Transactions
            "CREATE TABLE IF NOT EXISTS `wallet_transactions` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `wallet_id` int(11) NOT NULL,
              `type` enum('deposit','withdrawal','payment','transfer_in','transfer_out','fine','membership','registration_fee') NOT NULL,
              `amount` decimal(15,2) NOT NULL,
              `description` text DEFAULT NULL,
              `reference` varchar(255) DEFAULT NULL,
              `status` enum('pending','completed','failed') NOT NULL DEFAULT 'pending',
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Push Subscriptions
            "CREATE TABLE IF NOT EXISTS `push_subscriptions` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `endpoint` text NOT NULL,
              `p256dh_key` varchar(255) NOT NULL,
              `auth_key` varchar(255) NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `endpoint_unique` (`endpoint`(512))
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Referee Reports
            "CREATE TABLE IF NOT EXISTS `referee_reports` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fixture_id` int(11) NOT NULL,
              `referee_id` int(11) NOT NULL,
              `incident_type` varchar(50) NOT NULL,
              `minute` int(11) DEFAULT NULL,
              `description` text NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Injuries
            "CREATE TABLE IF NOT EXISTS `injuries` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `player_id` int(11) NOT NULL,
              `injury_description` varchar(255) NOT NULL,
              `start_date` date NOT NULL,
              `expected_return_date` date DEFAULT NULL,
              `status` enum('Active','Recovering','Fit') NOT NULL DEFAULT 'Active',
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Player Suspensions
            "CREATE TABLE IF NOT EXISTS `player_suspensions` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `player_id` int(11) NOT NULL,
              `reason` varchar(255) NOT NULL,
              `fixture_incurred_id` int(11) DEFAULT NULL,
              `matches_to_serve` int(11) NOT NULL DEFAULT 1,
              `status` enum('Active','Served') NOT NULL DEFAULT 'Active',
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // --- NEW TABLES FROM DUMP ---
            "CREATE TABLE IF NOT EXISTS `announcements` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `title` varchar(255) NOT NULL,
              `content` text NOT NULL,
              `type` enum('news','alert','info') NOT NULL DEFAULT 'news',
              `is_active` tinyint(1) NOT NULL DEFAULT 1,
              `created_by` int(11) NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `club_managers` (
              `user_id` int(11) NOT NULL,
              `club_id` int(11) NOT NULL,
              `role_title` varchar(100) NOT NULL,
              PRIMARY KEY (`user_id`,`club_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_leagues` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(255) NOT NULL,
              `creator_user_id` int(11) NOT NULL,
              `season` varchar(50) NOT NULL,
              `join_code` varchar(10) NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `join_code` (`join_code`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_league_members` (
              `league_id` int(11) NOT NULL,
              `fantasy_team_id` int(11) NOT NULL,
              PRIMARY KEY (`league_id`,`fantasy_team_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_player_points` (
              `player_id` int(11) NOT NULL,
              `gameweek` int(11) NOT NULL,
              `fixture_id` int(11) NOT NULL,
              `points` int(11) NOT NULL,
              `minutes_played` int(11) DEFAULT 0,
              `breakdown` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`breakdown`)),
              PRIMARY KEY (`player_id`,`gameweek`,`fixture_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_squads` (
              `fantasy_team_id` int(11) NOT NULL,
              `player_id` int(11) NOT NULL,
              `gameweek_added` int(11) DEFAULT NULL,
              `is_starter` tinyint(1) NOT NULL DEFAULT 0,
              `is_captain` tinyint(1) NOT NULL DEFAULT 0,
              `is_vice_captain` tinyint(1) NOT NULL DEFAULT 0,
              `bench_order` int(11) DEFAULT NULL,
              `formation` varchar(10) DEFAULT NULL,
              PRIMARY KEY (`fantasy_team_id`,`player_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_teams` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `name` varchar(100) NOT NULL,
              `season` varchar(20) NOT NULL,
              `bank` decimal(10,1) NOT NULL DEFAULT 100.0,
              `total_points` int(11) NOT NULL DEFAULT 0,
              `gameweek_points` int(11) NOT NULL DEFAULT 0,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `free_transfers` int(11) NOT NULL DEFAULT 1,
              `last_gw_update` int(11) DEFAULT 0,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_team_gameweek_stats` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fantasy_team_id` int(11) NOT NULL,
              `gameweek` int(11) NOT NULL,
              `points` int(11) DEFAULT 0,
              PRIMARY KEY (`id`),
              UNIQUE KEY `unique_team_gameweek` (`fantasy_team_id`,`gameweek`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fantasy_transfers` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fantasy_team_id` int(11) NOT NULL,
              `gameweek` int(11) NOT NULL,
              `player_out_id` int(11) NOT NULL,
              `player_in_id` int(11) NOT NULL,
              `transfer_time` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fines` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `entity_type` enum('club','player') NOT NULL,
              `entity_id` int(11) NOT NULL,
              `reason` varchar(255) NOT NULL,
              `amount` decimal(10,2) NOT NULL,
              `status` enum('unpaid','paid') NOT NULL DEFAULT 'unpaid',
              `issued_date` timestamp NOT NULL DEFAULT current_timestamp(),
              `paid_date` timestamp NULL DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `fixture_lineups` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fixture_id` int(11) NOT NULL,
              `team_id` int(11) NOT NULL,
              `player_id` int(11) NOT NULL,
              `lineup_status` enum('Starting','Substitute') NOT NULL,
              `formation` varchar(20) DEFAULT NULL,
              `played_position` varchar(50) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `fixture_team_player_unique` (`fixture_id`,`team_id`,`player_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `gameweeks` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `league_id` int(11) NOT NULL,
              `season_name` varchar(50) NOT NULL,
              `gameweek_number` int(11) NOT NULL,
              `deadline_time` datetime DEFAULT NULL,
              `is_finished` tinyint(1) DEFAULT 0,
              PRIMARY KEY (`id`),
              UNIQUE KEY `league_id` (`league_id`,`season_name`,`gameweek_number`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `gameweek_deadlines` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `league_id` int(11) NOT NULL,
              `season` varchar(50) NOT NULL,
              `gameweek` int(11) NOT NULL,
              `deadline_time` datetime NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `unique_deadline` (`league_id`,`season`,`gameweek`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `match_comments` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fixture_id` int(11) NOT NULL,
              `user_id` int(11) NOT NULL,
              `comment` text NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `match_events` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `fixture_id` int(11) NOT NULL,
              `team_id` int(11) NOT NULL,
              `player_id` int(11) DEFAULT NULL,
              `event_type` enum('goal','assist','yellow_card','red_card','substitution_in','substitution_out','corner','free_kick','shot_on_target','shot_off_target','foul','penalty_scored','penalty_missed','own_goal') NOT NULL,
              `minute` int(11) NOT NULL,
              `assisted_by_player_id` int(11) DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `memberships` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `club_id` int(11) NOT NULL,
              `membership_type` varchar(50) NOT NULL,
              `start_date` date NOT NULL,
              `expiry_date` date NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `membership_packages` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `club_id` int(11) NOT NULL,
              `name` varchar(100) NOT NULL,
              `description` text DEFAULT NULL,
              `price` decimal(10,2) NOT NULL,
              `duration_type` enum('monthly','termly','yearly') NOT NULL,
              `is_active` tinyint(1) NOT NULL DEFAULT 1,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `password_resets` (
              `email` varchar(100) NOT NULL,
              `token` varchar(255) NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp()
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `payments` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `amount` decimal(10,2) NOT NULL,
              `currency` varchar(10) NOT NULL,
              `transaction_ref` varchar(255) NOT NULL,
              `payment_gateway` varchar(50) NOT NULL,
              `status` varchar(50) NOT NULL,
              `metadata` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`metadata`)),
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `transaction_ref` (`transaction_ref`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `permissions` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(100) NOT NULL,
              `description` text DEFAULT NULL,
              `module` varchar(50) NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `name` (`name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `roles` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(50) NOT NULL,
              `description` text DEFAULT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `name` (`name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `role_permissions` (
              `role_id` int(11) NOT NULL,
              `permission_id` int(11) NOT NULL,
              PRIMARY KEY (`role_id`,`permission_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `seasons` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(50) NOT NULL,
              `is_active` tinyint(1) DEFAULT 1,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `name` (`name`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `training_attendance` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `session_id` int(11) NOT NULL,
              `player_id` int(11) NOT NULL,
              `status` enum('Present','Absent','Excused') NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `session_player_unique` (`session_id`,`player_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `training_sessions` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `team_id` int(11) NOT NULL,
              `session_date` date NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `transfers` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `player_id` int(11) NOT NULL,
              `from_club_id` int(11) NOT NULL,
              `to_club_id` int(11) NOT NULL,
              `offer_amount` decimal(12,2) DEFAULT NULL,
              `status` enum('pending','accepted','rejected','completed','cancelled') NOT NULL DEFAULT 'pending',
              `initiating_manager_id` int(11) NOT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `user_follows_clubs` (
              `user_id` int(11) NOT NULL,
              `club_id` int(11) NOT NULL,
              `followed_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`user_id`,`club_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            "CREATE TABLE IF NOT EXISTS `user_follows_players` (
              `user_id` int(11) NOT NULL,
              `player_id` int(11) NOT NULL,
              `followed_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`user_id`,`player_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
            
            // Sponsorship Packages
            "CREATE TABLE IF NOT EXISTS `sponsorship_packages` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `name` varchar(100) NOT NULL,
              `type` enum('league','match','fixture_list','ad') NOT NULL,
              `price` decimal(10,2) NOT NULL,
              `duration_days` int(11) DEFAULT NULL,
              `description` text,
              `is_active` tinyint(1) NOT NULL DEFAULT 1,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",

            // Sponsor Campaigns
            "CREATE TABLE IF NOT EXISTS `sponsor_campaigns` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `package_id` int(11) NOT NULL,
              `entity_id` int(11) DEFAULT NULL,
              `ad_content` varchar(255) NOT NULL,
              `ad_type` enum('image','video') NOT NULL DEFAULT 'image',
              `aggression` int(11) DEFAULT 1,
              `status` enum('pending','active','rejected','completed') NOT NULL DEFAULT 'active',
              `start_date` datetime DEFAULT NULL,
              `end_date` datetime DEFAULT NULL,
              `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",

            // --- DATA SEEDING ---
            // Roles
            "INSERT IGNORE INTO `roles` (`id`, `name`, `description`) VALUES
            (1, 'admin', 'General administrator with wide-ranging access.'),
            (2, 'club_manager', 'Manages a club, its teams, and staff.'),
            (3, 'commissioner', 'Manages live scoring for assigned matches.'),
            (4, 'fan', 'General user, can view content and play fantasy.'),
            (5, 'fantasy_manager', 'A user who plays fantasy football.'),
            (6, 'fixtures_manager', 'Manages league fixtures.'),
            (7, 'league_manager', 'Manages a specific league, its clubs and seasons.'),
            (8, 'player', 'A registered player in a team.'),
            (9, 'referee', 'Officiates matches.'),
            (10, 'super_admin', 'Has all permissions, including role management.'),
            (11, 'team_manager', 'Manages a specific team roster and lineups.'),
            (12, 'super_fantasy_manager', 'Manages the backend of the Fantasy module (prices, points, gameweeks).'),
            (13, 'finance_manager', 'Manages finances, withdrawals, and fines.'),
            (14, 'sponsor', 'Can run advertising campaigns.');",

            // Permissions
            "INSERT IGNORE INTO `permissions` (`id`, `name`, `description`, `module`) VALUES
            (1, 'leagues:create', 'Allow user to create new leagues', 'Leagues'),
            (2, 'leagues:edit', 'Allow user to edit existing leagues', 'Leagues'),
            (3, 'leagues:delete', 'Allow user to delete leagues', 'Leagues'),
            (4, 'leagues:view', 'Allow user to view league management pages', 'Leagues'),
            (5, 'seasons:create', 'Allow user to create new seasons', 'Seasons'),
            (6, 'seasons:edit', 'Allow user to edit existing seasons', 'Seasons'),
            (7, 'seasons:delete', 'Allow user to delete seasons', 'Seasons'),
            (8, 'seasons:view', 'Allow user to view season management', 'Seasons'),
            (9, 'gameweeks:create', 'Allow user to create new gameweeks', 'Gameweeks'),
            (10, 'gameweeks:edit', 'Allow user to edit gameweek details', 'Gameweeks'),
            (11, 'gameweeks:delete', 'Allow user to delete gameweeks', 'Gameweeks'),
            (12, 'gameweeks:view', 'Allow user to view gameweek management', 'Gameweeks'),
            (13, 'fixtures:create', 'Allow user to create new fixtures', 'Fixtures'),
            (14, 'fixtures:edit', 'Allow user to edit existing fixtures', 'Fixtures'),
            (15, 'fixtures:delete', 'Allow user to delete fixtures', 'Fixtures'),
            (16, 'fixtures:view', 'Allow user to view fixture management', 'Fixtures'),
            (17, 'fixtures:generate', 'Allow user to use the fixture generation tool', 'Fixtures'),
            (18, 'clubs:create', 'Allow user to create new clubs', 'Clubs'),
            (19, 'clubs:edit', 'Allow user to edit existing clubs', 'Clubs'),
            (20, 'clubs:delete', 'Allow user to delete clubs', 'Clubs'),
            (21, 'clubs:view', 'Allow user to view club management pages', 'Clubs'),
            (22, 'teams:create', 'Allow user to create new teams', 'Teams'),
            (23, 'teams:edit', 'Allow user to edit existing teams', 'Teams'),
            (24, 'teams:delete', 'Allow user to delete teams', 'Teams'),
            (25, 'teams:view', 'Allow user to view team management pages', 'Teams'),
            (26, 'rosters:approve', 'Allow user to approve or reject submitted rosters', 'Rosters'),
            (27, 'rosters:view', 'Allow user to view the roster management page', 'Rosters'),
            (28, 'users:create', 'Allow user to create new users', 'Users'),
            (29, 'users:edit', 'Allow user to edit user profiles and roles', 'Users'),
            (30, 'users:delete', 'Allow user to delete users', 'Users'),
            (31, 'users:view', 'Allow user to view the user management list', 'Users'),
            (32, 'roles:create', 'Allow user to create new roles', 'Roles & Permissions'),
            (33, 'roles:edit', 'Allow user to edit roles and assign permissions', 'Roles & Permissions'),
            (34, 'roles:delete', 'Allow user to delete roles', 'Roles & Permissions'),
            (35, 'roles:view', 'Allow user to view the roles management page', 'Roles & Permissions'),
            (36, 'fines:create', 'Allow user to issue new fines', 'Finance'),
            (37, 'fines:delete', 'Allow user to delete fines', 'Finance'),
            (38, 'fines:view', 'Allow user to view the fine management page', 'Finance'),
            (39, 'payments:view', 'Allow user to view all payment records', 'Finance'),
            (40, 'fantasy:manage_prices', 'Allow user to set fantasy player prices', 'Fantasy'),
            (41, 'fantasy:process_points', 'Allow user to run the fantasy points calculation engine', 'Fantasy'),
            (42, 'fantasy:season_rollover', 'Allow user to perform a full fantasy season reset', 'Fantasy'),
            (43, 'fantasy:view_management', 'Allow user to access the fantasy management dashboard', 'Fantasy'),
            (44, 'settings:edit', 'Allow user to change application-wide settings', 'System'),
            (45, 'announcements:create', 'Allow user to create and post announcements', 'System'),
            (46, 'announcements:delete', 'Allow user to delete announcements', 'System'),
            (369, 'wallets:view', 'Permission for wallets:view', ''),
            (370, 'wallets:manage', 'Permission for wallets:manage', ''),
            (371, 'withdrawals:view', 'Permission for withdrawals:view', ''),
            (372, 'withdrawals:manage', 'Permission for withdrawals:manage', ''),
            (373, 'finance:dashboard', 'Permission for finance:dashboard', '');",

            // Role Permissions
            "INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`) VALUES
            (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16), (1, 17), (1, 18), (1, 19), (1, 20), (1, 21), (1, 22), (1, 23), (1, 24), (1, 25), (1, 26), (1, 27), (1, 28), (1, 29), (1, 30), (1, 31), (1, 32), (1, 33), (1, 34), (1, 35), (1, 36), (1, 37), (1, 38), (1, 39), (1, 40), (1, 41), (1, 42), (1, 43), (1, 44), (1, 45), (1, 46),
            (2, 19), (2, 21), (2, 22), (2, 23), (2, 24), (2, 25), (2, 26), (2, 27), (2, 38), (2, 39),
            (3, 16),
            (6, 8), (6, 10), (6, 12), (6, 13), (6, 14), (6, 15), (6, 16), (6, 17),
            (7, 2), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15), (7, 16), (7, 17), (7, 21), (7, 25), (7, 26), (7, 27),
            (9, 16),
            (10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 10), (10, 11), (10, 12), (10, 13), (10, 14), (10, 15), (10, 16), (10, 17), (10, 18), (10, 19), (10, 20), (10, 21), (10, 22), (10, 23), (10, 24), (10, 25), (10, 26), (10, 27), (10, 28), (10, 29), (10, 30), (10, 31), (10, 32), (10, 33), (10, 34), (10, 35), (10, 36), (10, 37), (10, 38), (10, 39), (10, 40), (10, 41), (10, 42), (10, 43), (10, 44), (10, 45), (10, 46),
            (11, 23), (11, 25), (11, 27),
            (12, 10), (12, 12), (12, 31), (12, 40), (12, 41), (12, 42), (12, 43),
            (13, 36), (13, 37), (13, 38), (13, 39), (13, 369), (13, 370), (13, 371), (13, 372), (13, 373);"
        ];

        foreach ($queries as $sql) {
            $pdo->exec($sql);
        }

        // 4. Create Super Admin User
        $hashed_pass = password_hash($admin_pass, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash, role, first_name, last_name) VALUES (?, ?, ?, 'super_admin', 'Super', 'Admin') ON DUPLICATE KEY UPDATE password_hash = VALUES(password_hash)");
        $stmt->execute([$admin_user, $admin_email, $hashed_pass]);

        // 5. Insert Default Settings
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->execute(['app_name', $app_name]);
        $stmt->execute(['primary_color', '#2c3e50']);
        $stmt->execute(['secondary_color', '#3498db']);
        $stmt->execute(['system_currency', 'USD']);

        // 6. Generate .htaccess (Security & Optimization)
        $url_path = parse_url($site_url, PHP_URL_PATH) ?: '/';
        $url_path = rtrim($url_path, '/') . '/';

        $htaccess = "<IfModule mod_rewrite.c>\n";
        $htaccess .= "    RewriteEngine On\n";
        $htaccess .= "    RewriteBase $url_path\n";
        $htaccess .= "    # Redirect Trailing Slashes\n";
        $htaccess .= "    RewriteRule ^(.*)/$ $1 [L,R=301]\n\n";
        $htaccess .= "    # Handle Front Controller (if needed later)\n";
        $htaccess .= "    # RewriteCond %{REQUEST_FILENAME} !-d\n";
        $htaccess .= "    # RewriteCond %{REQUEST_FILENAME} !-f\n";
        $htaccess .= "    # RewriteRule ^ index.php [L]\n";
        $htaccess .= "</IfModule>\n\n";
        
        $htaccess .= "# Prevent directory listing\n";
        $htaccess .= "Options -Indexes\n\n";
        
        $htaccess .= "# Protect sensitive files\n";
        $htaccess .= "<FilesMatch \"^\.(env|config|git|sql)\">\n";
        $htaccess .= "    Order allow,deny\n";
        $htaccess .= "    Deny from all\n";
        $htaccess .= "</FilesMatch>\n\n";

        $htaccess .= "# Enable Gzip Compression\n";
        $htaccess .= "<IfModule mod_deflate.c>\n";
        $htaccess .= "    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json\n";
        $htaccess .= "</IfModule>\n\n";

        $htaccess .= "# Browser Caching\n";
        $htaccess .= "<IfModule mod_expires.c>\n";
        $htaccess .= "    ExpiresActive On\n";
        $htaccess .= "    ExpiresByType image/jpg \"access plus 1 year\"\n";
        $htaccess .= "    ExpiresByType image/jpeg \"access plus 1 year\"\n";
        $htaccess .= "    ExpiresByType image/gif \"access plus 1 year\"\n";
        $htaccess .= "    ExpiresByType image/png \"access plus 1 year\"\n";
        $htaccess .= "    ExpiresByType text/css \"access plus 1 month\"\n";
        $htaccess .= "    ExpiresByType application/pdf \"access plus 1 month\"\n";
        $htaccess .= "    ExpiresByType text/x-javascript \"access plus 1 month\"\n";
        $htaccess .= "    ExpiresByType application/javascript \"access plus 1 month\"\n";
        $htaccess .= "    ExpiresDefault \"access plus 2 days\"\n";
        $htaccess .= "</IfModule>\n";

        file_put_contents('.htaccess', $htaccess);

        // Protect core directory specifically
        if (!is_dir('core')) mkdir('core');
        file_put_contents('core/.htaccess', "Order deny,allow\nDeny from all");

        // 7. Generate robots.txt
        $robots = "User-agent: *\n";
        $robots .= "Disallow: /core/\n";
        $robots .= "Disallow: /admin/\n";
        $robots .= "Disallow: /app/includes/\n";
        $robots .= "Sitemap: $site_url/sitemap.xml\n";
        file_put_contents('robots.txt', $robots);

        // 8. Generate sitemap.xml
        $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $sitemap .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
        $sitemap .= "   <url>\n";
        $sitemap .= "      <loc>$site_url/app/index.php</loc>\n";
        $sitemap .= "      <lastmod>" . date('Y-m-d') . "</lastmod>\n";
        $sitemap .= "      <changefreq>daily</changefreq>\n";
        $sitemap .= "      <priority>1.0</priority>\n";
        $sitemap .= "   </url>\n";
        $sitemap .= "</urlset>";
        file_put_contents('sitemap.xml', $sitemap);

        $message = "Installation successful! You can now log in.";
        $msg_type = 'success';
        $step = 4;

    } catch (Exception $e) {
        $message = "Installation Error: " . $e->getMessage();
        $msg_type = 'error';
        $step = 2; // Revert to form
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Football Setup</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f4f7f6; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; color: #333; }
        .setup-container { background: white; padding: 2.5rem; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); width: 100%; max-width: 500px; }
        h1 { color: #2c3e50; text-align: center; margin-bottom: 1.5rem; font-size: 1.8rem; }
        .form-group { margin-bottom: 1.2rem; }
        label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #555; font-size: 0.9rem; }
        input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 1rem; transition: border-color 0.2s; }
        input:focus { border-color: #3498db; outline: none; }
        button { width: 100%; padding: 14px; background: #3498db; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 1.1rem; font-weight: 600; transition: background 0.2s; }
        button:hover { background: #2980b9; }
        .alert { padding: 15px; border-radius: 6px; margin-bottom: 1.5rem; font-size: 0.95rem; line-height: 1.5; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        h3 { border-bottom: 2px solid #f0f0f0; padding-bottom: 10px; margin-top: 2rem; margin-bottom: 1rem; color: #2c3e50; font-size: 1.2rem; }
        .success-actions { text-align: center; margin-top: 20px; }
        .btn-link { display: inline-block; text-decoration: none; background: #2ecc71; color: white; padding: 12px 25px; border-radius: 6px; font-weight: bold; }
        .check-item { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #eee; }
        .check-pass { color: #2ecc71; font-weight: bold; }
        .check-fail { color: #e74c3c; font-weight: bold; }
    </style>
</head>
<body>
    <div class="setup-container">
        <h1>Smart Football Setup</h1>
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $msg_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <?php if ($step === 1): ?>
            <?php
            $php_version = phpversion();
            $php_ok = version_compare($php_version, '7.4.0', '>=');
            $pdo_ok = extension_loaded('pdo_mysql');
            $mbstring_ok = extension_loaded('mbstring');
            $gd_ok = extension_loaded('gd');
            $openssl_ok = extension_loaded('openssl');

            // Check for write permissions on the core directory
            $core_dir = __DIR__ . '/core';
            $core_writable = false;
            if (is_dir($core_dir)) {
                $core_writable = is_writable($core_dir);
            } else {
                $core_writable = is_writable(__DIR__);
            }

            $all_ok = $php_ok && $pdo_ok && $mbstring_ok && $gd_ok && $openssl_ok && $core_writable;
            ?>
            <h3>1. System Check</h3>
            <div class="check-item">
                <span>PHP Version >= 7.4</span>
                <span class="<?php echo $php_ok ? 'check-pass' : 'check-fail'; ?>"><?php echo $php_version; ?></span>
            </div>
            <div class="check-item">
                <span>PDO MySQL Extension</span>
                <span class="<?php echo $pdo_ok ? 'check-pass' : 'check-fail'; ?>"><?php echo $pdo_ok ? 'Installed' : 'Missing'; ?></span>
            </div>
            <div class="check-item">
                <span>Mbstring Extension</span>
                <span class="<?php echo $mbstring_ok ? 'check-pass' : 'check-fail'; ?>"><?php echo $mbstring_ok ? 'Installed' : 'Missing'; ?></span>
            </div>
            <div class="check-item">
                <span>GD Library</span>
                <span class="<?php echo $gd_ok ? 'check-pass' : 'check-fail'; ?>"><?php echo $gd_ok ? 'Installed' : 'Missing'; ?></span>
            </div>
            <div class="check-item">
                <span>OpenSSL Extension</span>
                <span class="<?php echo $openssl_ok ? 'check-pass' : 'check-fail'; ?>"><?php echo $openssl_ok ? 'Installed' : 'Missing'; ?></span>
            </div>
            <div class="check-item">
                <span><code>core/</code> Writable</span>
                <span class="<?php echo $core_writable ? 'check-pass' : 'check-fail'; ?>"><?php echo $core_writable ? 'Writable' : 'Not Writable'; ?></span>
            </div>

            <form method="POST" style="margin-top: 20px;">
                <input type="hidden" name="step" value="2">
                <?php if ($all_ok): ?>
                    <button type="submit">Next Step</button>
                <?php else: ?>
                    <div class="alert alert-error">Please fix the issues above to continue.</div>
                    <button type="button" disabled style="opacity: 0.6; cursor: not-allowed;">Next Step</button>
                <?php endif; ?>
            </form>

        <?php elseif ($step === 2): ?>
        <form method="POST">
            <input type="hidden" name="step" value="3">
            
            <h3>2. Database Connection</h3>
            <div class="form-group"><label>Database Host</label><input type="text" name="db_host" value="localhost" required placeholder="e.g., localhost"></div>
            <div class="form-group"><label>Database Name</label><input type="text" name="db_name" required placeholder="e.g., smart_football"></div>
            <div class="form-group"><label>Database User</label><input type="text" name="db_user" required placeholder="e.g., root"></div>
            <div class="form-group"><label>Database Password</label><input type="password" name="db_pass" placeholder="Leave empty if none"></div>

            <h3>3. App Settings</h3>
            <div class="form-group"><label>App Name</label><input type="text" name="app_name" value="Smart Football" required></div>
            <div class="form-group"><label>Site Root URL</label><input type="url" name="site_url" value="<?php echo "http://$_SERVER[HTTP_HOST]" . dirname($_SERVER['PHP_SELF']); ?>" required placeholder="https://yourdomain.com/app"></div>

            <h3>4. Super Admin Account</h3>
            <div class="form-group"><label>Username</label><input type="text" name="admin_user" required placeholder="admin"></div>
            <div class="form-group"><label>Email</label><input type="email" name="admin_email" required placeholder="admin@example.com"></div>
            <div class="form-group"><label>Password</label><input type="password" name="admin_pass" required></div>

            <button type="submit">Install Application</button>
        </form>
        <?php elseif ($step === 4): ?>
            <div class="success-actions">
                <p>The application has been successfully installed.</p>
                <p style="color: #e74c3c; font-size: 0.9rem;"><strong>Important:</strong> Please delete this <code>setup.php</code> file from your server immediately.</p>
                <a href="app/login.php" class="btn-link">Go to Login</a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>