<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';
$db = getDB();

// 🛠️ TEMPORARY AUTO-FIX INJECTOR: Force-reset the password to a clean version via native PHP
$new_clean_password = "adminpassword2026"; 
$new_clean_hash = password_hash($new_clean_password, PASSWORD_BCRYPT);
$db->query("UPDATE admin_users SET password_hash = '$new_clean_hash' WHERE admin_id = '998877'");

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


if (!$data) {
    echo json_encode(["success" => false, "message" => "Invalid Payload Format"]);
    exit;
}

// ✨ ADVANCED PROTECTION: Explicitly trim inputs to strip out any accidental hidden whitespace characters
$admin_id = trim($db->real_escape_string($data['admin_id'] ?? ''));
$password = trim($data['password'] ?? '');

if (empty($admin_id) || empty($password)) {
    echo json_encode(["success" => false, "message" => "Missing Identity Fields"]);
    exit;
}

$result = $db->query("SELECT * FROM admin_users WHERE admin_id = '$admin_id' LIMIT 1");

if ($result && $result->num_rows > 0) {
    $admin = $result->fetch_assoc();
    
    // Cryptographically verify input against our stored hash string
    if (password_verify($password, $admin['password_hash'])) {
        echo json_encode([
            "success" => true,
            "message" => "Authenticated Successfully",
            "admin" => [
                "id" => $admin['id'],
                "admin_id" => $admin['admin_id'],
                "name" => $admin['name']
            ]
        ]);
        exit;
    } else {
        // 🔍 DIAGNOSTIC FAIL REASON A: User exists but password string didn't cross-reference perfectly
        echo json_encode([
            "success" => false, 
            "message" => "Password verification failed. Double-check capitalization."
        ]);
        exit;
    }
}

// 🔍 DIAGNOSTIC FAIL REASON B: The Admin ID doesn't even exist in the table rows
echo json_encode([
    "success" => false, 
    "message" => "Admin ID '$admin_id' not found in database records."
]);