<?php
// Start session
session_start();

// Database connection details
require 'dbconfig/dbconfig.php';

header('Content-Type: application/json');

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Initialize response array
    $response = [];

    // Retrieve and sanitize form data
    $name = trim(htmlspecialchars($_POST['name']));
    $idNo = trim(htmlspecialchars($_POST['idNo']));
    $dob = trim(htmlspecialchars($_POST['dob']));
    $contactNo = trim(htmlspecialchars($_POST['contactNo']));
    $province = trim(htmlspecialchars($_POST['province']));
    $district = trim(htmlspecialchars($_POST['district']));

    // Check if user has already submitted the form
    $checkQuery = $conn->prepare("SELECT id FROM users WHERE id_number = ? AND contact_no = ?");
    $checkQuery->bind_param("ss", $idNo, $contactNo);
    $checkQuery->execute();
    $checkQuery->store_result();

    if ($checkQuery->num_rows > 0) {
        $response = ["status" => "error", "message" => "You have already submitted the form."];
        echo json_encode($response);
        $checkQuery->close();
        $conn->close();
        exit;
    }
    $checkQuery->close();

    // Insert data into the database
    $stmt = $conn->prepare("INSERT INTO users (name, id_number, dob, contact_no, province, district) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss", $name, $idNo, $dob, $contactNo, $province, $district);

    if ($stmt->execute()) {
        $userID = $stmt->insert_id; // Get last inserted ID
        $_SESSION['user_id'] = $userID; // Store in session

        $stmt1 = $conn->prepare("SELECT COUNT(*) AS winner_count FROM users");
       
        // Execute winner count query
        if ($stmt1->execute()) {
            $stmt1->bind_result($winnerCount);
            $stmt1->fetch();
            $_SESSION['spinner_count'] = $winnerCount; // Store winner count in session
        }

        $response = [
            "status" => "success",
            "message" => "Successfully inserted",
            "userID" => $userID,
            "spinCount" => $_SESSION['spinner_count']
        ];

    } else {
        $response = ["status" => "error", "message" => "Database error: " . $stmt->error];
    }

    // Close statement and connection
    $stmt->close();
    $conn->close();

    // Send response
    echo json_encode($response);
} else {
    // If not a POST request
    $response = ["status" => "error", "message" => "Invalid request method"];
    echo json_encode($response);
}
?>
