<?php
// Use a more robust path to the bootstrap file
require_once dirname(__DIR__) . '/core/bootstrap.php';

function run_install() {
    $db = new Database();
    echo "<h3>Starting Demo Data Installation...</h3>";

    try {
        // --- Truncate tables to ensure a clean install without dropping them ---
        $tables_to_truncate = [
            'match_reports', 'match_events', 'fantasy_player_points', 'fantasy_transfers',
            'fantasy_league_members', 'fantasy_leagues', 'fantasy_squads', 'fantasy_teams',
            'match_lineups', 'fixtures', 'players', 'training_attendance', 'training_sessions',
            'club_managers', 'teams', 'clubs', 'seasons', 'leagues', 'settings', 'users'
        ];
        
        $db->query('SET FOREIGN_KEY_CHECKS = 0');
        $db->execute();

        foreach ($tables_to_truncate as $table) {
            try {
                $db->query("TRUNCATE TABLE `$table`");
                $db->execute();
            } catch (PDOException $e) {
                // Ignore errors for tables that might not exist yet on a very first run
            }
        }

        $db->query('SET FOREIGN_KEY_CHECKS = 1');
        $db->execute();

        // --- 1. Create Users ---
        $users = [
            ['username' => 'superadmin', 'email' => 'superadmin@app.com', 'password' => 'password', 'first_name' => 'Super', 'last_name' => 'Admin', 'role' => 'super_admin'],
            ['username' => 'admin', 'email' => 'admin@app.com', 'password' => 'password', 'first_name' => 'Main', 'last_name' => 'Admin', 'role' => 'admin'],
            ['username' => 'leaguemanager', 'email' => 'league.manager@app.com', 'password' => 'password', 'first_name' => 'League', 'last_name' => 'Manager', 'role' => 'league_manager'],
            ['username' => 'clubmanager', 'email' => 'club.manager@app.com', 'password' => 'password', 'first_name' => 'Club', 'last_name' => 'Manager', 'role' => 'club_manager'],
            ['username' => 'teammanager', 'email' => 'team.manager@app.com', 'password' => 'password', 'first_name' => 'Team', 'last_name' => 'Manager', 'role' => 'team_manager'],
            ['username' => 'teammanager2', 'email' => 'team.manager2@app.com', 'password' => 'password', 'first_name' => 'Second', 'last_name' => 'Manager', 'role' => 'team_manager'],
            ['username' => 'referee', 'email' => 'referee@app.com', 'password' => 'password', 'first_name' => 'Match', 'last_name' => 'Referee', 'role' => 'referee'],
            ['username' => 'commissioner', 'email' => 'commissioner@app.com', 'password' => 'password', 'first_name' => 'Match', 'last_name' => 'Commissioner', 'role' => 'commissioner'],
            ['username' => 'fan1', 'email' => 'fan1@app.com', 'password' => 'password', 'first_name' => 'John', 'last_name' => 'Doe', 'role' => 'fan'],
            ['username' => 'fan2', 'email' => 'fan2@app.com', 'password' => 'password', 'first_name' => 'Jane', 'last_name' => 'Smith', 'role' => 'fan'],
        ];
        $userIds = [];
        $userModel = new User();
        foreach ($users as $userData) {
            $userData['password_hash'] = password_hash($userData['password'], PASSWORD_DEFAULT);
            $userModel->register($userData);
            $newUser = $userModel->findByEmail($userData['email']);
            if ($newUser) {
                $userIds[$userData['username']] = $newUser->id;
                $userModel->updateRole($newUser->id, $userData['role']);
            }
        }
        echo "-> Users created successfully.<br>";

        // --- 2. Create Season & League ---
        $seasonModel = new Season();
        $seasonModel->create('2023/2024');
        $season = $seasonModel->getAll()[0];
        echo "-> Season '{$season->name}' created.<br>";

        $leagueModel = new League();
        $league_id = $leagueModel->create(['name' => 'Premier League', 'country' => 'Zambia', 'season' => $season->name, 'manager_id' => $userIds['leaguemanager'], 'logo' => null]);
        echo "-> League 'Premier League' created.<br>";

        // --- 3. Create Clubs & Teams ---
        $clubModel = new Club();
        $teamModel = new Team();
        $club_names = ['Nkana FC', 'Zesco United', 'Green Buffaloes', 'Power Dynamos', 'Red Arrows', 'Kabwe Warriors', 'Nkwazi FC', 'Buildcon FC', 'Forest Rangers', 'Lumwana Radiants', 'Mufulira Wanderers', 'Napsa Stars', 'Green Eagles', 'Indeni FC', 'Kansanshi Dynamos', 'Prison Leopards'];
        $team_ids = [];
        foreach ($club_names as $i => $club_name) {
            $club_id = $clubModel->create(['name' => $club_name, 'stadium' => $club_name . ' Stadium', 'league_id' => $league_id, 'logo' => null]);
            $team_id = $teamModel->create(['name' => 'Senior Team', 'club_id' => $club_id]);
            $team_ids[$club_name] = $team_id;
        }
        $teamModel->assignManager($team_ids['Nkana FC'], $userIds['teammanager']);
        $teamModel->assignManager($team_ids['Zesco United'], $userIds['teammanager2']);
        echo "-> 16 Clubs and their Senior Teams created.<br>";

        // --- 4. Create Players ---
        $playerModel = new Player();
        $first_names = ['Bwalya', 'Chisamba', 'Fashion', 'Enock', 'Patson', 'Kennedy', 'Stoppila', 'Frank', 'Augustine', 'Kings', 'Lameck', 'Evans', 'Justin', 'Clatous', 'Larry'];
        $last_names = ['Mwepu', 'Lungu', 'Sakala', 'Mwape', 'Daka', 'Mweene', 'Sunzu', 'Musonda', 'Mulenga', 'Kangwa', 'Banda', 'Shonga', 'Chama', 'Bwalya', 'Tembo'];
        $positions = ['Goalkeeper', 'Defender', 'Midfielder', 'Forward'];
        $player_user_ids = [];

        foreach ($team_ids as $team_id) {
            for ($i = 1; $i <= 15; $i++) {
                $fn = $first_names[array_rand($first_names)];
                $ln = $last_names[array_rand($last_names)];
                $username = 'p_' . strtolower(substr($fn, 0, 1) . $ln) . rand(10, 99);
                $email = $username . '@player.com';

                if ($userModel->findByUsername($username) || $userModel->findByEmail($email)) {
                    $username .= rand(100, 999);
                    $email = $username . '@player.com';
                }

                $user_data = ['username' => $username, 'email' => $email, 'password_hash' => password_hash('password', PASSWORD_DEFAULT), 'first_name' => $fn, 'last_name' => $ln];
                $userModel->register($user_data);
                $new_player_user = $userModel->findByEmail($email);
                $userModel->updateRole($new_player_user->id, 'player');

                $player_data = [
                    'user_id' => $new_player_user->id,
                    'team_id' => $team_id,
                    'position' => $positions[($i-1) % 4], // Distribute positions
                    'price' => number_format(rand(40, 125) / 10, 1),
                    'squad_number' => $i
                ];
                $db->query('INSERT INTO players (user_id, team_id, position, price, squad_number) VALUES (:user_id, :team_id, :position, :price, :squad_number)');
                foreach($player_data as $key => $value) { $db->bind(':' . $key, $value); }
                $db->execute();
                $player_user_ids[] = $new_player_user->id;
            }
        }
        echo "-> 240 Players created and assigned to teams.<br>";

        // --- 5. Create Fixtures (Past & Upcoming) ---
        $fixtureModel = new Fixture();
        $nkana_team_id = $team_ids['Nkana FC'];
        $zesco_team_id = $team_ids['Zesco United'];

        // Past Fixture
        $past_fixture_id = $fixtureModel->create([
            'league_id' => $league_id, 'home_team_id' => $nkana_team_id, 'away_team_id' => $zesco_team_id,
            'match_datetime' => date('Y-m-d H:i:s', strtotime('-7 days')), 'gameweek' => 1, 'status' => 'finished', 'venue' => 'Nkana Stadium',
            'home_team_score' => 2, 'away_team_score' => 1
        ]);

        // Upcoming Fixtures
        $fixtureModel->create([
            'league_id' => $league_id, 'home_team_id' => $team_ids['Green Buffaloes'], 'away_team_id' => $team_ids['Power Dynamos'],
            'match_datetime' => date('Y-m-d H:i:s', strtotime('+3 days')), 'gameweek' => 2, 'status' => 'scheduled', 'venue' => 'Green Buffaloes Stadium'
        ]);
        $fixtureModel->create([
            'league_id' => $league_id, 'home_team_id' => $team_ids['Red Arrows'], 'away_team_id' => $team_ids['Kabwe Warriors'],
            'match_datetime' => date('Y-m-d H:i:s', strtotime('+3 days')), 'gameweek' => 2, 'status' => 'scheduled', 'venue' => 'Red Arrows Stadium'
        ]);
        echo "-> Past and upcoming fixtures created.<br>";

        // --- 6. Create Lineups & Events for Past Fixture ---
        $lineupModel = new Lineup();
        $eventModel = new MatchEvent();
        $nkana_players = $playerModel->getPlayersByTeamId($nkana_team_id);
        $zesco_players = $playerModel->getPlayersByTeamId($zesco_team_id);

        // Nkana Lineup & Events
        $nkana_starters = array_slice(array_map(fn($p) => $p->id, $nkana_players), 0, 11);
        $nkana_subs = array_slice(array_map(fn($p) => $p->id, $nkana_players), 11, 4);
        $lineupModel->saveLineup($past_fixture_id, $nkana_team_id, $nkana_starters, $nkana_subs);
        $eventModel->log(['fixture_id' => $past_fixture_id, 'team_id' => $nkana_team_id, 'player_id' => $nkana_starters[10], 'event_type' => 'goal', 'minute' => 25, 'assisted_by_player_id' => $nkana_starters[8]]);
        $eventModel->log(['fixture_id' => $past_fixture_id, 'team_id' => $nkana_team_id, 'player_id' => $nkana_starters[3], 'event_type' => 'yellow_card', 'minute' => 40]);
        $eventModel->log(['fixture_id' => $past_fixture_id, 'team_id' => $nkana_team_id, 'player_id' => $nkana_starters[9], 'event_type' => 'goal', 'minute' => 78, 'assisted_by_player_id' => null]);

        // Zesco Lineup & Events
        $zesco_starters = array_slice(array_map(fn($p) => $p->id, $zesco_players), 0, 11);
        $zesco_subs = array_slice(array_map(fn($p) => $p->id, $zesco_players), 11, 4);
        $lineupModel->saveLineup($past_fixture_id, $zesco_team_id, $zesco_starters, $zesco_subs);
        $eventModel->log(['fixture_id' => $past_fixture_id, 'team_id' => $zesco_team_id, 'player_id' => $zesco_starters[10], 'event_type' => 'goal', 'minute' => 55, 'assisted_by_player_id' => $zesco_starters[7]]);
        echo "-> Lineups and match events logged for past fixture.<br>";

        // --- 7. Create Fantasy Data ---
        $fantasyModel = new Fantasy();
        $fantasySquadModel = new FantasySquad();
        $fantasyLeagueModel = new FantasyLeague();

        // Create team for fan1
        $fan1_team_id = $fantasyModel->create(['user_id' => $userIds['fan1'], 'name' => 'Doe\'s Dominators', 'season' => $season->name]);

        // Create squad for fan1
        $squad_player_ids = array_slice($player_user_ids, 0, 15);
        $fantasySquadModel->setSquad($fan1_team_id, $squad_player_ids, 1);

        // Create a league (created by fan2)
        $league_data = ['name' => 'The Office League', 'user_id' => $userIds['fan2'], 'season' => $season->name];
        $new_league = $fantasyLeagueModel->create($league_data);

        if ($new_league) {
            // Now, add fan1's team to the newly created league
            $fantasyLeagueModel->addMember($new_league->id, $fan1_team_id);
        }
        echo "-> Fantasy team, squad, and league created for demo user.<br>";

        echo "<h4>Installation Complete!</h4>";

    } catch (Exception $e) {
        echo "<h4 style='color: red;'>An error occurred during installation: " . $e->getMessage() . "</h4>";
    }
}

function run_delete($silent = false) {
    $db = new Database();
    if (!$silent) {
        echo "<h3>Starting Data Deletion...</h3>";
    }

    $tables = [
        'match_reports',
        'match_events',
        'fantasy_player_points',
        'fantasy_transfers',
        'fantasy_league_members',
        'fantasy_leagues',
        'fantasy_squads',
        'fantasy_teams',
        'match_lineups',
        'fixtures',
        'players',
        'training_attendance',
        'training_sessions',
        'club_managers',
        'teams',
        'clubs',
        'seasons',
        'leagues',
        'settings',
        'users'
    ];

    try {
        $db->query('SET FOREIGN_KEY_CHECKS = 0');
        $db->execute();

        foreach ($tables as $table) {
            try {
                $db->query("DROP TABLE IF EXISTS `$table`");
                $db->execute();
                if (!$silent) echo "-> Table `$table` dropped.<br>";
            } catch (PDOException $e) {
                if (!$silent) echo "<span style='color: orange;'>-> Could not drop table `$table` (may not exist).</span><br>";
            }
        }

        $db->query('SET FOREIGN_KEY_CHECKS = 1');
        $db->execute();

        if (!$silent) {
            echo "<h4>All application data has been deleted. Run setup.php to rebuild the schema.</h4>";
        }
    } catch (Exception $e) {
        echo "<h4 style='color: red;'>An error occurred during deletion: " . $e->getMessage() . "</h4>";
        // Attempt to re-enable foreign key checks
        try {
            $db->query('SET FOREIGN_KEY_CHECKS = 1');
            $db->execute();
        } catch (Exception $e2) {}
    }
}

$action = $_GET['action'] ?? null;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo Data Management</title>
    <style>
        body { font-family: sans-serif; line-height: 1.6; padding: 20px; }
        .container { max-width: 800px; margin: auto; border: 1px solid #ccc; padding: 20px; border-radius: 5px; }
        .actions { display: flex; gap: 1rem; }
        .actions a, .actions a:visited {
            display: inline-block;
            padding: 10px 20px;
            border-radius: 5px;
            text-decoration: none;
            color: white;
            font-weight: bold;
        }
        .install-btn { background-color: #28a745; }
        .delete-btn { background-color: #dc3545; }
        .setup-btn { background-color: #007bff; }
        .output { background-color: #f4f4f4; border: 1px solid #ddd; padding: 15px; margin-top: 20px; font-family: monospace; font-size: 14px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Demo Data Management</h1>
        <p>Use these actions to populate your database with sample data or to clear it completely.</p>
        <p><strong>Warning:</strong> "Delete All Data" will drop all tables. You must run `setup.php` again to rebuild the schema before installing demo data.</p>
        <div class="actions">
            <a href="setup.php" class="setup-btn">1. Run Schema Setup</a>
            <a href="?action=install" class="install-btn">2. Install Demo Data</a>
            <a href="?action=delete" onclick="return confirm('Are you sure you want to DROP all application tables? This cannot be undone.');" class="delete-btn">Delete All Data (DROP TABLES)</a>
        </div>

        <?php if ($action): ?>
            <div class="output">
                <?php
                if ($action === 'install') {
                    run_install();
                } elseif ($action === 'delete') {
                    run_delete();
                } else {
                    echo "Invalid action.";
                }
                ?>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>