<?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["admin"]) || !isset($_SESSION["admin"]["id"])) {
        $response["message"] = "Admin not logged in.";
        echo json_encode($response);
        exit;
    }

    $admin_id = $_SESSION["admin"]["id"];

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

    $rs = Database::search("SELECT * FROM `admin` WHERE `id` = '" . $admin_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"],
            "fname" => $row["fname"] ?? "",
            "lname" => $row["lname"] ?? "",
            "email" => $row["email"] ?? "",
            "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"
        ];

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

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

echo json_encode($response);
exit;

