<?php
include 'config.php';

date_default_timezone_set("Asia/Dhaka");

$now = date("Y-m-d H:i:s");

$result = $conn->query("SELECT * FROM match_schedule WHERE status='pending'");

while ($row = $result->fetch_assoc()) {

    $created = (int)$row['created_count'];
    $total = (int)$row['total_match'];

    if ($created >= $total) {
        $conn->query("UPDATE match_schedule SET status='completed' WHERE id=".$row['id']);
        continue;
    }

    $next_time = strtotime($row['start_time']) + ($created * $row['interval_minute'] * 60);

    if (time() >= $next_time) {

        $num = str_pad($created + 1, 2, "0", STR_PAD_LEFT);
        $title = $row['match_title']." ".$num;

        $insert = $conn->prepare("
            INSERT INTO freefire (
                match_title, match_time, total_prize, per_kill, entry_fee,
                entry_type, match_type, version, play_map, registration,
                total_player, prize_details, room_id, room_pass, match_result, timer, join_type
            )
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        ");

        $room_id = "NO";
        $room_pass = "NO";
        $match_result = "NO";

        $insert->bind_param(
            "sssssssssssssssss",
            $title,
            $row['match_time'],
            $row['total_prize'],
            $row['per_kill'],
            $row['entry_fee'],
            $row['entry_type'],
            $row['match_type'],
            $row['version'],
            $row['play_map'],
            $row['registration'],
            $row['total_player'],
            $row['prize_details'],
            $room_id,
            $room_pass,
            $match_result,
            $row['timer'],
            $row['join_type']
        );

        $insert->execute();
        $insert->close();

        $conn->query("UPDATE match_schedule SET created_count = created_count + 1 WHERE id=".$row['id']);
    }
}

$conn->close();
?>