<?php
// Suppress any output before JSON
ob_start();

session_start();
include "connection.php";
include "validation.php";

// Clear any output buffer
ob_clean();

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

$response = [
    "status" => false,
    "message" => "",
    "new_status" => null
];

try {
    // optional: check admin session if required
    // if (!isset($_SESSION["user"]["id"])) { $response["message"]="Unauthorized."; echo json_encode($response); exit; }

    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    $id = isset($data["id"]) ? intval($data["id"]) : 0;
    if ($id <= 0) {
        $response["message"] = "Invalid student id.";
        echo json_encode($response);
        exit;
    }

    $rs = Database::search("SELECT `student_status_id` FROM `student` WHERE `id` = '". $id ."'");
    if ($rs === false || $rs->num_rows != 1) {
        $response["message"] = "Student not found.";
        echo json_encode($response);
        exit;
    }

    $row = $rs->fetch_assoc();
    $current = intval($row["student_status_id"]);
    
    // Toggle between Active (1) and Deactive (2)
    // If current is 1 (Active), change to 2 (Deactive)
    // If current is 2 (Deactive), change to 1 (Active)
    // If current is anything else, default to 1 (Active)
    if ($current === 1) {
        $newStatus = 2; // Change to Deactive
    } else if ($current === 2) {
        $newStatus = 1; // Change to Active
    } else {
        $newStatus = 1; // Default to Active for any other status
    }

    // Update the database
    Database::iud("UPDATE `student` SET `student_status_id` = '". $newStatus ."' WHERE `id` = '". $id ."'");

    // Verify the update was successful
    $verify_rs = Database::search("SELECT `student_status_id` FROM `student` WHERE `id` = '". $id ."'");
    if ($verify_rs && $verify_rs->num_rows === 1) {
        $verify_row = $verify_rs->fetch_assoc();
        $actualStatus = intval($verify_row["student_status_id"]);
        
        // Fetch readable status value from student_status table
        $status_rs = Database::search("SELECT `value` FROM `student_status` WHERE `id` = '". $actualStatus ."' LIMIT 1");
        $status_text = ($status_rs && $status_rs->num_rows == 1) ? $status_rs->fetch_assoc()["value"] : ($actualStatus == 1 ? "Active" : "Deactive");

        $response["status"] = true;
        $response["message"] = "Student status updated successfully.";
        $response["new_status"] = $actualStatus;
        $response["new_status_text"] = $status_text;
    } else {
        $response["message"] = "Status update failed - could not verify update.";
    }
} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
