<?php
include('session.php'); // Ensure session and DB connection

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'updateRecord';
    $recordId = trim($_POST['recordid']);
    $strname= strtoupper($_POST['name']);
    $strnric = strtoupper($_POST['nric']);
    $strage= strtoupper($_POST['age']);
    $stremail = strtoupper($_POST['email']);
    $strcontactno = strtoupper($_POST['contactno']);
    $strschool = strtoupper($_POST['school']);
    $strcat= strtoupper($_POST['cat']);

    $response = array();

    // Validate common input
    if (empty($recordId)) {
        $response['error'] = 'Invalid record.';
        echo json_encode($response);
        exit;
    }

    if ($action === "updateRecord") {
        $stmt = $conn->prepare("UPDATE $tblquizict2026 SET FullName = ?, NRICMyKid = ?, Age = ?, EmailAdd = ?, ContactNo = ?, SchoolName = ?, Category = ? WHERE AutoIndex = ?");
        if ($stmt === false) {
            $response['error'] = "RALAT: Penyediaan SQL gagal.";
        } else {
            $stmt->bind_param("ssssssss", $strname, $strnric, $strage, $stremail, $strcontactno, $strschool, $strcat, $recordId);

            if ($stmt->execute()) {
                $response['success'] = "Record updated!";
            } else {
                $response['error'] = "Error: Update record!";
            }

            $stmt->close();
        }
    } 

    $conn->close();
    echo json_encode($response);

} else {
    echo json_encode(array('error' => 'Method error.'));
}
?>