<?php
date_default_timezone_set('Asia/Dhaka');
header('Content-Type: application/json');

require 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    exit;
}

$start_code = trim($_POST['start_code'] ?? '');

if ($start_code === '') {
    echo json_encode([
        "status" => "failed",
        "message" => "Start Code Required"
    ]);
    exit;
}

$result = $conn->query("SELECT username, password, device_id, fcm_key, extra_json FROM users");

if (!$result) {
    echo json_encode([
        "status" => "failed",
        "message" => "Database Error"
    ]);
    exit;
}

while ($row = $result->fetch_assoc()) {
    $json = json_decode($row['extra_json'] ?? '', true);

    if (!is_array($json)) {
        continue;
    }

    if (!isset($json['start_code']) || $json['start_code'] !== $start_code) {
        continue;
    }

    $saved_time_text = $json['start_code_date_and_full_time'] ?? '';
    $saved_time = strtotime($saved_time_text);

    if ($saved_time === false) {
        echo json_encode([
            "status" => "failed",
            "message" => "Invalid Time"
        ]);
        exit;
    }

    $now = time();
    $diff = $now - $saved_time;

    if ($diff > 300) {
        echo json_encode([
            "status" => "failed",
            "message" => "Timer Expired"
        ]);
        exit;
    }

    echo json_encode([
        "status" => "success",
        "username" => $row['username'],
        "password" => $row['password'],
        "device_id" => $row['device_id'],
        "fcm_key" => $row['fcm_key']
    ]);
    exit;
}

echo json_encode([
    "status" => "failed",
    "message" => "Start Code Not Found"
]);