<?php
header('Content-Type: application/json; charset=utf-8');

include 'connection.php';
include 'decrypt_and_validate.php';   // for API key validation

$response = [];

try {
    $api_key = $_POST['API_Key'] ?? '';

    // Validate API key
    $validation = validateApiKey($api_key);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }

    // Fetch App_Setting values (assuming only one row)
    $stmt = $conn->prepare("SELECT Notice, Up_Coming_Draw_Date, Up_Coming_Draw_Number, App_On_Off, Last_Past_Draw_Date, Last_Past_Draw_Number FROM App_Setting LIMIT 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();

    if ($row) {
        $response = [
            "status" => "success",
            "notice" => $row['Notice'],
            "upcoming_date" => $row['Up_Coming_Draw_Date'],
            "upcoming_number" => $row['Up_Coming_Draw_Number'],
            "last_Past_Draw_Date" => $row['Last_Past_Draw_Date'],
            "last_Past_Draw_Number" => $row['Last_Past_Draw_Number'],
            "app_on_off" => $row['App_On_Off']
        ];
    } else {
        throw new Exception("No app settings found.");
    }

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

echo json_encode($response);
?>
