<?php
require_once '../core/bootstrap.php';

// --- Security Check ---
$is_cli = (php_sapi_name() === 'cli');
$is_super_admin = (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin');

if (!$is_cli && !$is_super_admin) {
    die('Access Denied. You must be logged in as a Super Admin to run this script.');
}

$db = new Database();
echo "<h1>Installing Demo Content (Leagues, Clubs, Teams, Players)</h1>";

// 1. Ensure League Exists
$db->query("SELECT id FROM leagues WHERE name = 'Zambian Super League'");
$league = $db->single();
if (!$league) {
    $db->query("INSERT INTO leagues (name, country, season) VALUES ('Zambian Super League', 'Zambia', '2024/2025')");
    $db->execute();
    $league_id = $db->lastInsertId();
    echo "Created League: Zambian Super League<br>";
} else {
    $league_id = $league->id;
    echo "League exists: Zambian Super League<br>";
}

// 2. Create Clubs & Teams
$clubs_data = [
    ['name' => 'Nkana FC', 'stadium' => 'Nkana Stadium'],
    ['name' => 'Zesco United', 'stadium' => 'Levy Mwanawasa Stadium'],
    ['name' => 'Power Dynamos', 'stadium' => 'Arthur Davies Stadium'],
    ['name' => 'Zanaco FC', 'stadium' => 'Sunset Stadium'],
    ['name' => 'Red Arrows', 'stadium' => 'Nkoloma Stadium'],
    ['name' => 'Green Buffaloes', 'stadium' => 'Independence Stadium'],
    ['name' => 'Forest Rangers', 'stadium' => 'Levy Mwanawasa Stadium'],
    ['name' => 'NAPSA Stars', 'stadium' => 'Woodlands Stadium'],
    ['name' => 'Kabwe Warriors', 'stadium' => 'Godfrey Chitalu Stadium'],
    ['name' => 'Green Eagles', 'stadium' => 'Independence Stadium (Choma)']
];

$team_ids = [];

foreach ($clubs_data as $c) {
    // Check/Create Club
    $db->query("SELECT id FROM clubs WHERE name = :name");
    $db->bind(':name', $c['name']);
    $club = $db->single();
    
    if (!$club) {
        $db->query("INSERT INTO clubs (name, stadium, league_id) VALUES (:name, :stadium, :league_id)");
        $db->bind(':name', $c['name']);
        $db->bind(':stadium', $c['stadium']);
        $db->bind(':league_id', $league_id);
        $db->execute();
        $club_id = $db->lastInsertId();
        echo "Created Club: {$c['name']}<br>";
    } else {
        $club_id = $club->id;
    }

    // Check/Create Team
    $db->query("SELECT id FROM teams WHERE club_id = :club_id AND name = 'Senior Team'");
    $db->bind(':club_id', $club_id);
    $team = $db->single();

    if (!$team) {
        $db->query("INSERT INTO teams (name, club_id) VALUES ('Senior Team', :club_id)");
        $db->bind(':club_id', $club_id);
        $db->execute();
        $tid = $db->lastInsertId();
        echo "Created Team for {$c['name']}<br>";
    } else {
        $tid = $team->id;
    }
    $team_ids[$c['name']] = $tid;
}

// 3. Create Zesco United Manager
$zesco_team_id = $team_ids['Zesco United'];
$mgr_email = 'zesco_manager@example.com';
$db->query("SELECT id FROM users WHERE email = :email");
$db->bind(':email', $mgr_email);
$mgr = $db->single();

if (!$mgr) {
    $pass = password_hash('password', PASSWORD_DEFAULT);
    $db->query("INSERT INTO users (first_name, last_name, username, email, password_hash, role) VALUES ('George', 'Lwandamina', 'zesco_coach', :email, :pass, 'team_manager')");
    $db->bind(':email', $mgr_email);
    $db->bind(':pass', $pass);
    $db->execute();
    $mgr_id = $db->lastInsertId();
    echo "Created Zesco Manager: $mgr_email (Password: password)<br>";
} else {
    $mgr_id = $mgr->id;
    echo "Zesco Manager exists.<br>";
}

// Assign manager to team
$db->query("UPDATE teams SET manager_id = :mgr_id WHERE id = :tid");
$db->bind(':mgr_id', $mgr_id);
$db->bind(':tid', $zesco_team_id);
$db->execute();

// 4. Create Players
$positions_template = array_merge(
    array_fill(0, 2, 'Goalkeeper'),
    array_fill(0, 6, 'Defender'),
    array_fill(0, 6, 'Midfielder'),
    array_fill(0, 4, 'Forward')
); // 18 players per team

$first_names = ['John', 'Peter', 'James', 'Moses', 'Kennedy', 'Joseph', 'Emmanuel', 'Brian', 'Collins', 'Isaac', 'Gift', 'Andrew', 'Patrick', 'Lazarus', 'Festus', 'Simon', 'David', 'Solomon'];
$last_names = ['Banda', 'Phiri', 'Mulenga', 'Sakala', 'Chilufya', 'Mwape', 'Zulu', 'Musonda', 'Chama', 'Lungu', 'Ngoma', 'Mwanza', 'Nyirenda', 'Tembo', 'Kangwa', 'Sinyangwe', 'Daka', 'Sinkala'];

foreach ($team_ids as $club_name => $tid) {
    // Check if team already has players
    $db->query("SELECT COUNT(*) as count FROM players WHERE team_id = :tid");
    $db->bind(':tid', $tid);
    if ($db->single()->count > 0) {
        echo "Skipping players for $club_name (already has players).<br>";
        continue;
    }

    echo "Adding players to $club_name... ";
    $count = 0;
    foreach ($positions_template as $idx => $pos) {
        $fname = $first_names[array_rand($first_names)];
        $lname = $last_names[array_rand($last_names)];
        $email = strtolower(preg_replace('/[^a-z0-9]/', '', $club_name) . ".{$idx}@example.com");
        
        // Check if user exists
        $db->query("SELECT id FROM users WHERE email = :email");
        $db->bind(':email', $email);
        if (!$db->single()) {
            $pass = password_hash('password', PASSWORD_DEFAULT);
            $db->query("INSERT INTO users (first_name, last_name, username, email, password_hash, role) VALUES (:f, :l, :u, :e, :p, 'player')");
            $db->bind(':f', $fname);
            $db->bind(':l', $lname);
            $db->bind(':u', strtolower("{$fname}_{$lname}_{$tid}_{$idx}"));
            $db->bind(':e', $email);
            $db->bind(':p', $pass);
            $db->execute();
            $uid = $db->lastInsertId();

            // Add to players table
            $squad_num = $idx + 1;
            $price = rand(40, 120) / 10; // 4.0 to 12.0
            
            $db->query("INSERT INTO players (user_id, team_id, position, squad_number, fantasy_price) VALUES (:uid, :tid, :pos, :num, :price)");
            $db->bind(':uid', $uid);
            $db->bind(':tid', $tid);
            $db->bind(':pos', $pos);
            $db->bind(':num', $squad_num);
            $db->bind(':price', $price);
            $db->execute();
            $count++;
        }
    }
    echo "$count added.<br>";
}

echo "<br><strong>Demo Content Installation Complete!</strong>";
?>