<?php
// --- TAMIM 1280 MASTER FIX START (অটোমেটিক ডিরেক্টরি ডিটেকশন) ---
$sessionPath = __DIR__ . '/sessions'; 
if (!file_exists($sessionPath)) { 
    @mkdir($sessionPath, 0755, true); 
}
if (is_writable($sessionPath)) {
    ini_set('session.save_path', $sessionPath);
}
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// --- TAMIM 1280 MASTER FIX END ---

// লগইন চেক
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

include 'db.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System Processing...</title>
    <!-- স্টাইল লোড -->
    <link rel="stylesheet" href="css/style.css?v=<?php echo time(); ?>">
    <style>
        /* সেভ পেজের জন্য স্পেশাল স্টাইল */
        body {
            display: flex; flex-direction: column;
            justify-content: center; align-items: center;
            text-align: center;
            background-color: #050505;
        }
        .loader-box {
            border: 1px solid #00eaff;
            padding: 40px;
            border-radius: 10px;
            background: rgba(10, 20, 30, 0.9);
            box-shadow: 0 0 30px rgba(0, 234, 255, 0.2);
            max-width: 400px; width: 90%;
        }
        .loading-text {
            font-family: 'Orbitron', sans-serif;
            font-size: 20px; color: #00eaff;
            margin-top: 20px; letter-spacing: 2px;
            animation: blink 1.5s infinite;
        }
        .loading-bar {
            width: 100%; height: 4px;
            background: #333; margin-top: 15px;
            position: relative; overflow: hidden;
        }
        .loading-bar::after {
            content: ''; position: absolute; top: 0; left: 0;
            width: 50%; height: 100%; background: #00eaff;
            animation: slide 1s infinite ease-in-out;
        }
        .error-msg { color: #ff3333; font-family: 'Rajdhani', sans-serif; font-size: 18px; margin-top: 10px; }
        
        @keyframes slide { 0% { left: -50%; } 100% { left: 100%; } }
        @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
    </style>
</head>
<body>

<div class="loader-box">
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        
        // ইনপুট ভ্যালিডেশন
        if (!isset($_POST['title']) || !isset($_POST['players'])) {
            echo "<h2 style='color:red;'>⚠️ SYSTEM ERROR: DATA MISSING</h2>";
            echo "<a href='index.php' style='color:#fff;'>RETURN TO SYSTEM</a>";
            exit();
        }

        $title = $conn->real_escape_string($_POST['title']);
        $type = $_POST['game_type'];
        $total = $_POST['total_players'];
        $players_data = $_POST['players'];

        // ১. ম্যাচ ডাটাবেসে সেভ করা
        $sql = "INSERT INTO matches (title, game_type, total_players) VALUES ('$title', '$type', '$total')";
        
        if ($conn->query($sql) === TRUE) {
            $match_id = $conn->insert_id;
            
            // ২. প্লেয়ারদের ডাটাবেসে সেভ করা
            $stmt = $conn->prepare("INSERT INTO match_participants (match_id, team_number, player_name, player_role) VALUES (?, ?, ?, ?)");

            foreach ($players_data as $team_num => $team_members) {
                foreach ($team_members as $member) {
                    $p_name = $member['name']; // ফর্ম থেকে নাম
                    $p_role = $member['role']; // ফর্ম থেকে রোল

                    $final_name = trim($p_name);
                    if ($final_name == "") $final_name = "EMPTY"; // সেফটি

                    $stmt->bind_param("iiss", $match_id, $team_num, $final_name, $p_role);
                    $stmt->execute();
                }
            }
            $stmt->close();

            // ✅ সফল হলে সুন্দর এনিমেশন এবং রিডাইরেক্ট
            echo "<h1 style='color:#fff; font-family:Orbitron;'>PROCESSING DATA</h1>";
            echo "<div class='loading-bar'></div>";
            echo "<div class='loading-text'>SAVING TO SYSTEM...</div>";
            
            // ২ সেকেন্ড পর view.php তে নিয়ে যাবে (JavaScript দিয়ে)
            echo "<script>
                    setTimeout(function(){
                        window.location.href = 'view.php?id=$match_id';
                    }, 2000);
                  </script>";

        } else {
            echo "<h2 class='error-msg'>DATABASE ERROR: " . $conn->error . "</h2>";
        }

    } else {
        echo "<h2 class='error-msg'>⚠️ UNAUTHORIZED ACCESS</h2>";
    }
    
    $conn->close();
    ?>
</div>

</body>
</html>