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

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

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

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

try {
    if ($role == 'admin') {
        $query = $dbh->prepare('SELECT * FROM admin WHERE UserName =:userName');
        $query->bindParam(':userName', $userName);
        $query->execute();
        $row = $query->fetch(PDO::FETCH_ASSOC);
        // User not found
        if (!$row) {
            echo json_encode([
                "status" => "error",
                "message" => "User not found"
            ]);
            exit;
        }

        // User found → verify password
        if (password_verify($rawpassword, $row['Password'])) {
            if ($row) {
                if ($row['FullName'] != 'Admin Bluebase') {
                    // Insert login log
                    $ip = $_SERVER['REMOTE_ADDR'];
                    $sqlLog = "INSERT INTO tbladminlogs (AdminId, loginTime, ipAddress, appLogin) 
                    VALUES (:adminId, :currentTime, :ip, :adminId)";
                    $queryLog = $dbh->prepare($sqlLog);
                    $queryLog->bindParam(':adminId', $row['id'], PDO::PARAM_INT);
                    $queryLog->bindParam(':currentTime', $currentTime, PDO::PARAM_STR);
                    $queryLog->bindParam(':ip', $ip, PDO::PARAM_STR);
                    $queryLog->execute();
                }

                echo json_encode([
                    "status" => "success",
                    "student" => $row
                ]);
            } else {
                echo json_encode(["status" => "error", "message" => "Invalid UserName or password" . $rawpassword]);
            }
            exit;
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid password" . $rawpassword]);
        }

        // $stmt = $dbh->prepare("SELECT * FROM admin WHERE Password = :password AND UserName = :userName");
        // $stmt->bindParam(':userName', $userName);
        // $stmt->bindParam(':password', $password);
        // $stmt->execute();

        // $row = $stmt->fetch(PDO::FETCH_ASSOC);
        // if ($row) {
        //     if ($row['FullName'] != 'Admin Bluebase') {
        //         // Insert login log
        //         $ip = $_SERVER['REMOTE_ADDR'];
        //         $sqlLog = "INSERT INTO tbladminlogs (AdminId, loginTime, ipAddress, appLogin) 
        //             VALUES (:adminId, :currentTime, :ip, :adminId)";
        //         $queryLog = $dbh->prepare($sqlLog);
        //         $queryLog->bindParam(':adminId', $row['id'], PDO::PARAM_INT);
        //         $queryLog->bindParam(':currentTime', $currentTime, PDO::PARAM_STR);
        //         $queryLog->bindParam(':ip', $ip, PDO::PARAM_STR);
        //         $queryLog->execute();
        //     }

        //     echo json_encode([
        //         "status" => "success",
        //         "student" => $row
        //     ]);
        // } else {
        //     echo json_encode(["status" => "error", "message" => "Invalid UserName or password" . $rawpassword]);
        // }
    } else if ($role == 'staff') {
        $stmt = $dbh->prepare("SELECT * FROM tblstaff WHERE EmailId = :email AND Password = :password");
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $password);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            echo json_encode([
                "status" => "success",
                "student" => $row
            ]);
            exit;
        } else {
            echo json_encode(["status" => "error", "message" => "Missing fields"]);
        }
    } else if ($role == 'student') {
        $stmt = $dbh->prepare("SELECT * FROM tblstudents WHERE EmailId=:email and Password = :password");
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $password);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            echo json_encode([
                "status" => "success",
                "student" => $row
            ]);
        } else {
            echo json_encode(["status" => "error", "message" => "Missing fields"]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Missing fields"]);
    }
} catch (Exception $e) {
    echo json_encode([
        "status" => "error",
        "message" => 'Server Filed' #$e->getMessage()
    ]);
}

// if ($email && $password) {
//     $stmt = $dbh->prepare("SELECT * FROM admin WHERE Password = :password AND AdminEmail = :email");
//     $stmt->bindParam(':email', $email);
//     $stmt->bindParam(':password', $password);
//     $stmt->execute();

//     $row = $stmt->fetch(PDO::FETCH_ASSOC);

//     if ($row && isset($row['rights']) && $row['rights'] == 1) {
//         echo json_encode([
//             "status" => "success",
//             "student" => $row
//         ]);
//     } else {
//         $stmt = $dbh->prepare("SELECT * FROM tblstaff WHERE EmailId = :email AND Password = :password");
//         $stmt->bindParam(':email', $email);
//         $stmt->bindParam(':password', $password);
//         $stmt->execute();

//         $row = $stmt->fetch(PDO::FETCH_ASSOC);

//         if ($row) {
//             echo json_encode([
//                 "status" => "success",
//                 "student" => $row
//             ]);
//             exit;
//         } else {
//             $stmt = $dbh->prepare("SELECT * FROM tblstudents WHERE EmailId=:email and Password = :password");
//             $stmt->bindParam(':email', $email);
//             $stmt->bindParam(':password', $password);
//             $stmt->execute();

//             $row = $stmt->fetch(PDO::FETCH_ASSOC);
//             if ($row) {
//                 echo json_encode([
//                     "status" => "success",
//                     "student" => $row
//                 ]);
//             } else {
//                 echo json_encode([
//                     "status" => "error",
//                     "message" => "Invalid Email & Password",
//                     "debug_email" => $email,
//                     "debug_password" => $password
//                 ]);
//             }
//         }
//     }
// } 
// else {
//     echo json_encode(["status" => "error", "message" => "Missing fields"]);
// }
