<?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" => "",
    "data" => []
];

try {
    if (!isset($_SESSION["user"]) || !isset($_SESSION["user"]["id"])) {
        $response["message"] = "User not logged in.";
        echo json_encode($response);
        exit;
    }

    $student_id = $_SESSION["user"]["id"];

    // Sanitize student_id to prevent SQL injection
    $student_id = intval($student_id);
    if ($student_id <= 0) {
        $response["message"] = "Invalid student ID.";
        echo json_encode($response);
        exit;
    }

    $rs = Database::search("SELECT * FROM `student` WHERE `id` = '" . $student_id . "'");

    // Check if query was successful
    if ($rs === false) {
        $response["message"] = "Database query failed.";
        echo json_encode($response);
        exit;
    }

    if ($rs && $rs->num_rows === 1) {
        $row = $rs->fetch_assoc();

        // map DB column names to friendly keys used by frontend
        $data = [
            "id" => $row["id"],
            "first_name" => $row["firstName"] ?? "",
            "last_name" => $row["lastName"] ?? "",
            "email" => $row["email"] ?? "",
            "nic" => $row["nic"] ?? "",
            "mobile" => $row["mobile"] ?? "",
            "password" => $row["password"] ?? "",
            // store profile image path in "profile_image" (frontend uses this name)
            "profile_image" => !empty($row["profile_img"]) ? $row["profile_img"] : "Resources/Images/Profile.jpg",
            "registered_date" => $row["registerd_date"] ?? ""
        ];

        $response["status"] = true;
        $response["data"] = $data;
    } else {
        $response["message"] = "Student not found.";
    }

} catch (Exception $e) {
    $response["message"] = "Error: " . $e->getMessage();
} catch (Error $e) {
    $response["message"] = "Error: " . $e->getMessage();
}

echo json_encode($response);
exit;
