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

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

    if (!$data) {
        $response["message"] = "Invalid request data.";
        echo json_encode($response);
        exit;
    }

    $email = isset($data["email"]) ? trim($data["email"]) : "";
    $password = isset($data["password"]) ? trim($data["password"]) : "";

    // Validation
    if (empty($email)) {
        $response["message"] = "Please Enter Email Address";
        echo json_encode($response);
        exit;
    }

    if (empty($password)) {
        $response["message"] = "Please Enter Password";
        echo json_encode($response);
        exit;
    }

    if (!isValidEmail($email)) {
        $response["message"] = "Please enter a valid email address";
        echo json_encode($response);
        exit;
    }

    // Ensure database connection is established
    Database::setUpConnection();
    
    // Sanitize inputs to prevent SQL injection
    if (Database::$connection) {
        $email = mysqli_real_escape_string(Database::$connection, $email);
        $password = mysqli_real_escape_string(Database::$connection, $password);
    }

    // Search for admin
    $rs = Database::search("SELECT * FROM `admin` WHERE `email` = '" . $email . "' AND `password` = '" . $password . "'");
    
    if ($rs === false) {
        $response["message"] = "Database error occurred.";
        echo json_encode($response);
        exit;
    }

    $rows = $rs->num_rows;

    if ($rows == 1) {
        $user = $rs->fetch_assoc();
        $_SESSION["admin"] = $user;

        $response["status"] = true;
        $response["message"] = "Admin Login Success!";
    } else {
        $response["status"] = false;
        $response["message"] = "Invalid email or password";
    }

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

echo json_encode($response);
exit;
