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

// --- Security Check ---
// Only allow access if running from CLI or if logged in as Super Admin
$is_cli = (php_sapi_name() === 'cli');
$is_super_admin = (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin');

// Allow running if no users exist yet (first install)
$db = new Database();
$db->query("SELECT COUNT(*) as count FROM users");
$user_count = $db->single()->count;

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

echo "<h1>Resetting Users & Creating Demo Accounts</h1>";

// 1. Wipe existing users
// We disable FK checks to avoid errors with related tables (like players, clubs, etc.)
$db->query("SET FOREIGN_KEY_CHECKS = 0");
$db->execute();

$db->query("DROP TABLE IF EXISTS users");
$db->execute();

$db->query("CREATE TABLE `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,
  `password_hash` varchar(255) NOT NULL,
  `role` varchar(50) NOT NULL DEFAULT 'fan',
  `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");
$db->execute();
echo "Users table recreated.<br>";

// Recreate players table to ensure correct schema
$db->query("DROP TABLE IF EXISTS players");
$db->execute();

$db->query("CREATE TABLE `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`),
  KEY `user_id` (`user_id`),
  KEY `team_id` (`team_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$db->execute();
echo "Players table recreated.<br>";

// Recreate fantasy_teams table
$db->query("DROP TABLE IF EXISTS fantasy_teams");
$db->execute();
$db->query("CREATE TABLE `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,
  `free_transfers` int(11) NOT NULL DEFAULT 1,
  `last_gw_update` int(11) DEFAULT 0,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `fantasy_teams_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$db->execute();
echo "Fantasy Teams table recreated.<br>";

// Recreate fantasy_squad table
$db->query("DROP TABLE IF EXISTS fantasy_squads");
$db->execute();
$db->query("CREATE TABLE `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;");
$db->execute();
echo "Fantasy Squads table recreated.<br>";

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

// 2. Create Demo Users
$password_hash = password_hash('password', PASSWORD_DEFAULT);

$demo_users = [
    ['super_admin', 'Super', 'Admin'],
    ['admin', 'Demo', 'Admin'],
    ['league_manager', 'League', 'Manager'],
    ['fixtures_manager', 'Fixtures', 'Manager'],
    ['club_manager', 'Club', 'Manager'],
    ['team_manager', 'Team', 'Manager'],
    ['super_fantasy_manager', 'Fantasy', 'SuperAdmin'],
    ['commissioner', 'Match', 'Commissioner'],
    ['referee', 'Match', 'Referee'],
    ['fan', 'Demo', 'Fan'],
    ['player', 'Demo', 'Player'],
    ['fantasy_manager', 'Fantasy', 'Manager'],
    ['finance_manager', 'Finance', 'Manager']
];

foreach ($demo_users as $u) {
    $role = $u[0];
    $fname = $u[1];
    $lname = $u[2];
    $username = $role . '_demo';
    $email = $role . '@example.com';

    $db->query("INSERT INTO users (first_name, last_name, username, email, password_hash, role, created_at) VALUES (:f, :l, :u, :e, :p, :r, NOW())");
    $db->bind(':f', $fname);
    $db->bind(':l', $lname);
    $db->bind(':u', $username);
    $db->bind(':e', $email);
    $db->bind(':p', $password_hash);
    $db->bind(':r', $role);
    $db->execute();
    
    echo "Created: <strong>$username</strong> ($role) - Email: $email<br>";
}

echo "<br><strong>Done!</strong> All passwords are 'password'. <a href='../app/login.php'>Go to Login</a>";
?>