<?php
header("Content-Type: application/json");
require_once "../config.php";

$role =  $_POST['role'] ?? $_GET['role'] ?? '';
$email = $_POST['email'] ?? $_GET['email'] ?? '';
$currentTime = $_POST['currentTime'] ??  $_GET['currentTime'] ?? '';

$password = $_POST['password'] ?? $_GET['password'] ?? '';

try {
    if ($role == 'admin') {
        $stmt = $dbh->prepare("SELECT * FROM admin WHERE AdminEmail = :email");
        $stmt->bindParam(':email', $email);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            if (password_verify($password, $row['Password'])) {
                if ($row['FullName'] != 'Admin Bluebase') {
                    // Insert logout log
                    $sqlLog = "UPDATE tbladminlogs SET logoutTime =:currentTime WHERE adminId= :adminId AND logoutTime IS NULL  ORDER BY `loginTime` DESC LIMIT 1;";
                    $queryLog = $dbh->prepare($sqlLog);
                    $queryLog->bindParam(':adminId', $row['id'], PDO::PARAM_INT);
                    $queryLog->bindParam(':currentTime', $currentTime, PDO::PARAM_STR);
                    $queryLog->execute();
                }
                echo json_encode([
                    "status" => "success",
                    "student" => $row
                ]);
            } else {
                echo json_encode(["status" => "error", "message" => "Invalid password"]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid email or password"]);
        }
    }
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => "Does Not Logout - $e"]);
}
