<?php
// Enable error reporting
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . "/aaaerror.txt");

// Database connection
$host = "localhost"; 
$user = "appshett_ibill"; 
$pass = "appshett_ibill"; 
$dbname = "appshett_ibill";

// Create a log function
function logError($message) {
    file_put_contents(__DIR__ . "/aaaerror.txt", "[" . date("Y-m-d H:i:s") . "] " . $message . "\n", FILE_APPEND);
}

$conn = new mysqli($host, $user, $pass, $dbname);

// Check connection
if ($conn->connect_error) {
    logError("Database connection failed: " . $conn->connect_error);
    die(json_encode(["error" => "Database connection failed"]));
}

// Ensure request method is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    logError("Received POST request");

    // Read JSON input
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!$data) {
        logError("Invalid JSON input: " . file_get_contents("php://input"));
        echo json_encode(["error" => "Invalid JSON input."]);
        exit;
    }

    if (!isset($data['slipType'], $data['idNumber'], $data['consent'])) {
        logError("Missing required fields in request: " . json_encode($data));
        echo json_encode(["error" => "Invalid input data."]);
        exit;
    }

    $slipType = $conn->real_escape_string($data['slipType']);
    $idNumber = $conn->real_escape_string($data['idNumber']);
    $consent = isset($data['consent']) ? 1 : 0;
    $timestamp = date("Y-m-d H:i:s");
    $trackingID = uniqid("VAL_");

    // Insert into database
    $sql = "INSERT INTO validation_request (tracking_id, slip_type, id_number, consent, created_at) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    
    if (!$stmt) {
        logError("Failed to prepare statement: " . $conn->error);
        echo json_encode(["error" => "Database error."]);
        exit;
    }

    $stmt->bind_param("sssis", $trackingID, $slipType, $idNumber, $consent, $timestamp);
    
    if ($stmt->execute()) {
        logError("Data inserted successfully: " . json_encode($data));

        // Store validation request in JSON file
        $logData = [
            "trackingID" => $trackingID,
            "slipType" => $slipType,
            "idNumber" => $idNumber,
            "consent" => $consent,
            "timestamp" => $timestamp
        ];
        file_put_contents(__DIR__ . "/validation.json", json_encode($logData, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);

        echo json_encode(["success" => true, "trackingID" => $trackingID]);
    } else {
        logError("Failed to insert data: " . $stmt->error);
        echo json_encode(["error" => "Failed to submit request."]);
    }

    $stmt->close();
} else {
    logError("Invalid request method: " . $_SERVER["REQUEST_METHOD"]);
}

$conn->close();
?>
