<?php
// Add at the VERY TOP of process-vote.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// Debug logging
function log_debug($message) {
    error_log("VOTE_DEBUG: " . $message);
}

log_debug("=== VOTE PROCESSING STARTED ===");
log_debug("Request Method: " . $_SERVER['REQUEST_METHOD']);
log_debug("Session User ID: " . ($_SESSION['user_id'] ?? 'NOT SET'));

require_once 'includes/database.php';

if(!isset($_SESSION['user_id'])) {
    log_debug("ERROR: User not logged in");
    $_SESSION['error'] = "You must be logged in to vote.";
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$vote_cost = 10; // 10 ZIT Coins per vote

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        log_debug("Processing POST request");
        
        $game_week = $_POST['game_week'] ?? null;
        
        log_debug("User ID: $user_id, Game Week: $game_week");
        
        if (!$game_week) {
            throw new Exception("Game week not specified.");
        }
        
        $pdo->beginTransaction();
        
        // Check user's coin balance FIRST
        $stmt = $pdo->prepare("SELECT balance FROM user_wallets WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $wallet = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $current_balance = $wallet['balance'] ?? 0;
        log_debug("User balance: $current_balance, Vote cost: $vote_cost");
        
        if($current_balance < $vote_cost) {
            throw new Exception("Insufficient ZIT Coins! You need {$vote_cost} coins to vote. Current balance: {$current_balance} coins. <a href='buy-coins.php' style='color: #007bff; text-decoration: underline;'>Buy more coins</a>");
        }
        
        // Get and validate selections
        $goalkeeper = isset($_POST['goalkeeper']) ? intval($_POST['goalkeeper']) : null;
        $defenders = isset($_POST['defenders']) ? array_map('intval', $_POST['defenders']) : [];
        $midfielders = isset($_POST['midfielders']) ? array_map('intval', $_POST['midfielders']) : [];
        $forwards = isset($_POST['forwards']) ? array_map('intval', $_POST['forwards']) : [];
        $coach = isset($_POST['coach']) ? intval($_POST['coach']) : null;
        
        log_debug("Selections - GK: $goalkeeper, DEF: " . count($defenders) . ", MID: " . count($midfielders) . ", FWD: " . count($forwards) . ", Coach: $coach");
        
        // Validate goalkeeper
        if(!$goalkeeper) {
            throw new Exception("Please select a goalkeeper.");
        }
        
        // Validate defenders (3-5)
        $defCount = count($defenders);
        if($defCount < 3) {
            throw new Exception("Please select at least 3 defenders.");
        }
        if($defCount > 5) {
            throw new Exception("Please select maximum 5 defenders.");
        }
        
        // Validate midfielders (3-5)
        $midCount = count($midfielders);
        if($midCount < 3) {
            throw new Exception("Please select at least 3 midfielders.");
        }
        if($midCount > 5) {
            throw new Exception("Please select maximum 5 midfielders.");
        }
        
        // Validate forwards (1-4)
        $fwdCount = count($forwards);
        if($fwdCount < 1) {
            throw new Exception("Please select at least 1 forward.");
        }
        if($fwdCount > 4) {
            throw new Exception("Please select maximum 4 forwards.");
        }
        
        // Validate coach
        if(!$coach) {
            throw new Exception("Please select a coach.");
        }
        
        // Validate total players = 11
        $totalPlayers = 1 + $defCount + $midCount + $fwdCount;
        if($totalPlayers !== 11) {
            throw new Exception("You must select exactly 11 players. Currently selected: $totalPlayers");
        }
        
        // DEDUCT COINS BEFORE VOTING
        log_debug("Deducting $vote_cost coins from user $user_id");
        $stmt = $pdo->prepare("UPDATE user_wallets SET balance = balance - ? WHERE user_id = ?");
        $stmt->execute([$vote_cost, $user_id]);
        
        // Record coin deduction transaction
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'vote', ?, ?)");
        $stmt->execute([$user_id, $vote_cost, "Vote submission - Game Week {$game_week}"]);
        
        // Prepare the insert statement for players
        $voteStmt = $pdo->prepare("INSERT INTO votes (user_id, player_id, game_week, created_at) VALUES (?, ?, ?, NOW())");
        
        // Insert goalkeeper vote
        log_debug("Inserting GK: $goalkeeper");
        $voteStmt->execute([$user_id, $goalkeeper, $game_week]);
        
        // Insert defender votes
        foreach($defenders as $defender) {
            if($defender > 0) {
                log_debug("Inserting DEF: $defender");
                $voteStmt->execute([$user_id, $defender, $game_week]);
            }
        }
        
        // Insert midfielder votes
        foreach($midfielders as $midfielder) {
            if($midfielder > 0) {
                log_debug("Inserting MID: $midfielder");
                $voteStmt->execute([$user_id, $midfielder, $game_week]);
            }
        }
        
        // Insert forward votes
        foreach($forwards as $forward) {
            if($forward > 0) {
                log_debug("Inserting FWD: $forward");
                $voteStmt->execute([$user_id, $forward, $game_week]);
            }
        }
        
        // Insert coach vote
        $coachStmt = $pdo->prepare("INSERT INTO votes (user_id, coach_id, game_week, created_at) VALUES (?, ?, ?, NOW())");
        log_debug("Inserting Coach: $coach");
        $coachStmt->execute([$user_id, $coach, $game_week]);
        
        $pdo->commit();
        
        log_debug("Vote submitted successfully");
        $_SESSION['success'] = "Your vote has been submitted successfully! {$vote_cost} ZIT Coins deducted. <a href='vote.php' style='color: #007bff; text-decoration: underline;'>Vote again</a>";
        header('Location: vote.php');
        exit;
        
    } catch(Exception $e) {
        $pdo->rollBack();
        $error_msg = "Error: " . $e->getMessage();
        log_debug($error_msg);
        $_SESSION['error'] = $error_msg;
        header('Location: vote.php');
        exit;
    }
} else {
    log_debug("ERROR: Not a POST request");
    $_SESSION['error'] = "Invalid request method.";
    header('Location: vote.php');
    exit;
}
?>