<?php
// 1. Force PHP to display all errors immediately so we don't get a blind 500 error
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<pre style='background:#222; color:#fff; padding:15px; border-radius:5px;'>";
echo "=== DIAGNOSTIC MODE ACTIVE ===\n";
echo "Step 1: Session initialization... ";
session_start();
echo "SUCCESS\n";

// --- MILESTONE 2: File Includes ---
echo "Step 2: Checking File Includes...\n";

if (!file_exists('../models/db_connection.php')) {
    die("CRITICAL ERROR: '../models/db_connection.php' file path does not exist!\n");
}
require_once '../models/db_connection.php';
echo " -> db_connection.php loaded\n";

if (!file_exists('../models/user_model.php')) {
    die("CRITICAL ERROR: '../models/user_model.php' file path does not exist!\n");
}
require_once '../models/user_model.php';
echo " -> user_model.php loaded\n";


// --- MILESTONE 3: Database Variable & Class Checking ---
echo "Step 3: Checking Database Connection Object...\n";
if (!isset($conn)) {
    die("CRITICAL ERROR: The variable '\$conn' is missing. Check your db_connection.php file.\n");
}
echo " -> \$conn exists: " . (is_object($conn) ? "Object (" . get_class($conn) . ")" : gettype($conn)) . "\n";


echo "Step 4: Instantiating User Class... ";
if (!class_exists('User')) {
    die("CRITICAL ERROR: Class 'User' not found inside user_model.php!\n");
}
try {
    $user = new User($conn);
    echo "SUCCESS\n";
} catch (Throwable $e) {
    die("CRITICAL ERROR during User instantiation: " . $e->getMessage() . "\n");
}


// --- MILESTONE 5: Form Submission Interception ---
if (isset($_POST["login"])) {
    echo "\n=== FORM SUBMISSION DETECTED ===\n";
    echo "Username provided: " . htmlspecialchars($_POST["username"]) . "\n";
    echo "Password provided: [HIDDEN] (Length: " . strlen($_POST["password"]) . ")\n";
    
    echo "Step 5: Executing \$user->login()... ";
    try {
        $userData = $user->login($_POST["username"], $_POST["password"]);
        echo "SUCCESS\n";
        
        echo "Returned Data Structure:\n";
        var_dump($userData);
        
        if ($userData && isset($userData[0])) {
            $loggeInUser = $userData[0];
            echo "User record found in array index [0].\n";
            echo "Hashed password in DB: " . ($loggeInUser['password'] ?? 'MISSING KEY') . "\n";
            
            echo "Step 6: Verifying Password... ";
            if (password_verify($_POST["password"], $loggeInUser['password'])) {
                echo "MATCHED!\n";
                $_SESSION['user'] = $loggeInUser['id'];
                $_SESSION['role'] = $loggeInUser['role'];
                echo "Sessions stored successfully. Redirecting would happen here.\n";
                // Commented out to prevent the redirect from clearing your diagnostic view:
                // header('Location: ../index.php');
                // exit();
            } else {
                echo "FAILED (Password mismatch)\n";
                $sms = 'Wrong username or password';
            }
        } else {
            echo "FAILED (No records returned or bad array format)\n";
            $sms = 'Wrong username or password';
        }
    } catch (Throwable $e) {
        die("CRITICAL ERROR running login() method: " . $e->getMessage() . "\n");
    }
} else {
    echo "\nNo active form POST data detected. Submit the form below to test Step 5 & 6.\n";
}
echo "===============================\n";
echo "</pre>";

// Rest of your template continues safely below...
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Regal Admin</title>
  <?php 
  echo "";
  if (file_exists("../templates/header.php")) {
      include("../templates/header.php"); 
  } else {
      echo "<p style='color:red;'>Warning: Header template not found</p>";
  }
  ?>
</head>

<body>
  <?php
      if (isset($_GET["message"])) {
        $message = htmlspecialchars($_GET["message"], ENT_QUOTES, 'UTF-8');
        echo "<script>alert('".$message."')</script>";
      }
  ?>
  <div class="container-scroller">
    <div class="container-fluid page-body-wrapper full-page-wrapper">
      <div class="content-wrapper d-flex align-items-center auth px-0">
        <div class="row w-100 mx-0">
          <div class="col-lg-4 mx-auto">
            <div class="auth-form-light text-left py-5 px-4 px-sm-5">
              
              <h4>Login Form (Diagnostic Mode)</h4>
              <h6 class="font-weight-light">Log in to your account</h6>
              <form class="pt-