<?php
error_reporting(0);
header('Content-Type: application/json');
include 'config.php';
$conn->set_charset("utf8mb4");

session_start();

$action = $_POST['action'] ?? '';

// ---------- Admin Login ----------
if ($action === 'login') {
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    
    $stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND password=? LIMIT 1");
    $stmt->bind_param("ss", $admin_username, $admin_password);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(["status" => "success", "message" => "Login Successful"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid Credentials!"]);
    }
    $stmt->close();
    exit;
}

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(["status" => "error", "message" => "Access Denied."]);
    exit;
}

// ---------- GET CATEGORIES ----------
if ($action === 'get_categories') {
    $sql = "SELECT id, title FROM category ORDER BY id DESC";
    $result = $conn->query($sql);
    $categories = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
    }
    echo json_encode(["status" => "success", "data" => $categories]);
    exit;
}

// ---------- GET ALL MATCHES ----------
if ($action === 'get_list') {
    $sql = "SELECT * FROM match_schedule ORDER BY id DESC";
    $result = $conn->query($sql);
    $data = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    echo json_encode(["status" => "success", "data" => $data]);
    exit;
}

// ---------- GET SINGLE MATCH ----------
if ($action === 'get_single') {
    $id = (int)($_POST['id'] ?? 0);
    $stmt = $conn->prepare("SELECT * FROM match_schedule WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        echo json_encode(["status" => "success", "data" => $row]);
    } else {
        echo json_encode(["status" => "error", "message" => "Data not found"]);
    }
    $stmt->close();
    exit;
}

// ---------- SAVE OR UPDATE ----------
if ($action === 'save') {
    $id = (int)($_POST['id'] ?? 0);
    
    $match_title = $_POST['match_title'] ?? '';
    $total_match = (int)($_POST['total_match'] ?? 0);
    $start_time_raw = $_POST['start_time'] ?? '';
    $interval_minute = (int)($_POST['interval_minute'] ?? 0);
    $match_time_raw = $_POST['match_time'] ?? '';
    $total_prize = $_POST['total_prize'] ?? '0';
    $per_kill = $_POST['per_kill'] ?? '0';
    $entry_fee = $_POST['entry_fee'] ?? '0';
    $entry_type = $_POST['entry_type'] ?? '';
    $match_type = $_POST['match_type'] ?? ''; 
    $version = $_POST['version'] ?? '';
    $play_map = $_POST['play_map'] ?? '';
    $registration = $_POST['registration'] ?? 'Open';
    $total_player = (int)($_POST['total_player'] ?? 0);
    $prize_details = $_POST['prize_details'] ?? '';
    $timer_raw = $_POST['timer'] ?? '';
    $join_type = $_POST['join_type'] ?? '';
    $status = $_POST['status'] ?? 'Active';
    $created_count = (int)($_POST['created_count'] ?? 0);

    if (empty($match_title) || empty($match_type)) {
        echo json_encode(["status" => "error", "message" => "Title and Match Type are required!"]);
        exit;
    }

    // Convert strict SQL formats (Removes the 'T' bug)
    $start_timestamp = strtotime($start_time_raw);
    $match_timestamp = strtotime($match_time_raw);
    $timer_timestamp = !empty($timer_raw) ? strtotime($timer_raw) : 0;

    if ($id > 0) {
        $start_time = date('Y-m-d H:i:s', $start_timestamp);
        $match_time = date('Y-m-d H:i:s', $match_timestamp);
        $timer = $timer_timestamp ? date('Y-m-d H:i:s', $timer_timestamp) : '';

        $sql = "UPDATE match_schedule SET 
                match_title=?, total_match=?, start_time=?, interval_minute=?, match_time=?, 
                total_prize=?, per_kill=?, entry_fee=?, entry_type=?, match_type=?, 
                version=?, play_map=?, registration=?, total_player=?, prize_details=?, 
                timer=?, join_type=?, status=?, created_count=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sisisssssssssisssssi", 
            $match_title, $total_match, $start_time, $interval_minute, $match_time, 
            $total_prize, $per_kill, $entry_fee, $entry_type, $match_type, 
            $version, $play_map, $registration, $total_player, $prize_details, 
            $timer, $join_type, $status, $created_count, $id);
            
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Match Schedule updated successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Database Error: " . $stmt->error]);
        }
        $stmt->close();
    } else {
        $sql = "INSERT INTO match_schedule (
                match_title, total_match, start_time, interval_minute, match_time, 
                total_prize, per_kill, entry_fee, entry_type, match_type, 
                version, play_map, registration, total_player, prize_details, 
                timer, join_type, status, created_count) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        
        $insert_count = $total_match > 0 ? $total_match : 1;
        $success = true;
        $error_msg = "";

        for ($i = 0; $i < $insert_count; $i++) {
            $added_minutes = $i * $interval_minute;
            
            $loop_start_time = date('Y-m-d H:i:s', strtotime("+$added_minutes minutes", $start_timestamp));
            $loop_match_time = date('Y-m-d H:i:s', strtotime("+$added_minutes minutes", $match_timestamp));
            $loop_timer = $timer_timestamp ? date('Y-m-d H:i:s', strtotime("+$added_minutes minutes", $timer_timestamp)) : '';
            
            $stmt->bind_param("sisisssssssssisssss", 
                $match_title, $total_match, $loop_start_time, $interval_minute, $loop_match_time, 
                $total_prize, $per_kill, $entry_fee, $entry_type, $match_type, 
                $version, $play_map, $registration, $total_player, $prize_details, 
                $loop_timer, $join_type, $status, $created_count);
                
            if (!$stmt->execute()) {
                $success = false;
                $error_msg = $stmt->error;
                break;
            }
        }
        
        if ($success) {
            echo json_encode(["status" => "success", "message" => "$insert_count Match Schedules added successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Database Error: " . $error_msg]);
        }
        $stmt->close();
    }
    exit;
}

// ---------- DELETE MATCH ----------
if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM match_schedule WHERE id = ?");
        $stmt->bind_param("i", $id);
        if($stmt->execute()){
            echo json_encode(["status" => "success", "message" => "Match deleted successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to delete!"]);
        }
        $stmt->close();
    }
    exit;
}
?>