<?php
// /admission33333/committee_login.php — robust includes + debug + secure login

/* ===== Debug toggle: add ?debug=1 to see errors on page ===== */
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);
  header("Content-Type: text/html; charset=UTF-8");
} else {
  error_reporting(E_ALL);
}

/* ===== Get role from URL parameter ===== */
$role = $_GET['role'] ?? 'committee'; // Default to 'committee' if no role specified

/* ===== Helper to locate required files no matter current dir ===== */
function req_path($fname) {
  $candidates = [
    __DIR__ . "/$fname",
    dirname(__DIR__) . "/$fname",
    __DIR__ . "/../$fname",
  ];
  foreach ($candidates as $p) {
    if (is_file($p)) return $p;
  }
  return null;
}

/* ===== Include db + helpers safely ===== */
$dbphp = req_path('db.php');
$helphp= req_path('helpers.php');

if (!$dbphp || !$helphp) {
  http_response_code(500);
  if ($DEBUG) {
    echo "<h3>Include error</h3>";
    echo "<p>Could not find <code>db.php</code> or <code>helpers.php</code> near " . e(__DIR__) . "</p>";
  }
  exit;
}

require_once $dbphp;
require_once $helphp;

/* ===== Ensure session ===== */
if (function_exists('session_status') && session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

/* ===== Ensure core helpers & DB handle exist ===== */
if (!function_exists('verify_csrf') || !function_exists('csrf_token')) {
  function csrf_token() { return $_SESSION['csrf'] = $_SESSION['csrf'] ?? bin2hex(random_bytes(16)); }
  function verify_csrf($t){ return isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], (string)$t); }
}
if (!function_exists('e')) {
  function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}

if (!isset($mysqli1) || !($mysqli1 instanceof mysqli)) {
  http_response_code(500);
  if ($DEBUG) {
    echo "<h3>DB error</h3><p><code>\$mysqli1</code> was not created by db.php.</p>";
  }
  exit;
}
$mysqli1->set_charset('utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/* ===== If already logged in, go to appropriate dashboard ===== */
if (!empty($_SESSION['committee_id'])) {
  $user_role = $_SESSION['user_role'] ?? 'committee';
  switch($user_role) {
    case 'accountant':
      header("Location: accountant_dashboard.php");
      exit;
    case 'card_printing':
      header("Location: card_printing_dashboard.php");
      exit;
    case 'committee':
    default:
      header("Location: committee_dashboard.php");
      exit;
  }
}

$error = '';
$username = '';

/* ===== Handle POST (login) ===== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    if (!verify_csrf($_POST['csrf'] ?? '')) {
      $error = 'Invalid session token.';
    } else {
      $username = trim((string)($_POST['username'] ?? ''));
      $password = (string)($_POST['password'] ?? '');

      if ($username === '' || $password === '') {
        $error = 'Username and password are required.';
      } else {
        $stmt = $mysqli1->prepare("SELECT id, username, password_hash, name, can_view_all, college_id, role_id FROM committee_users WHERE username=? LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        // COMPREHENSIVE DEBUGGING
        if ($user) {
          error_log("=== LOGIN DEBUG START ===");
          error_log("Username input: '" . $username . "'");
          error_log("Password input: '" . $password . "'");
          error_log("Stored hash: '" . $user['password_hash'] . "'");
          error_log("Stored hash length: " . strlen($user['password_hash']));
          error_log("Input password length: " . strlen($password));
          
          // Character-by-character analysis
          error_log("--- CHARACTER ANALYSIS ---");
          $max_len = max(strlen($user['password_hash']), strlen($password));
          for ($i = 0; $i < $max_len; $i++) {
            $stored_char = isset($user['password_hash'][$i]) ? 'char#' . $i . '=' . ord($user['password_hash'][$i]) . "('" . $user['password_hash'][$i] . "')" : 'END';
            $input_char = isset($password[$i]) ? 'char#' . $i . '=' . ord($password[$i]) . "('" . $password[$i] . "')" : 'END';
            if ($stored_char !== $input_char) {
              error_log("CHARACTER MISMATCH at position $i: stored=$stored_char, input=$input_char");
            }
          }
          
          $info = password_get_info($user['password_hash']);
          error_log("--- PASSWORD INFO ---");
          error_log("Algo: " . $info['algo']);
          error_log("AlgoName: " . $info['algoname']);
          error_log("Options: " . print_r($info['options'], true));
        } else {
          error_log("=== LOGIN DEBUG: USER NOT FOUND ===");
          error_log("Username searched: '" . $username . "'");
        }

        $ok = false;
        if ($user) {
          // Prefer strong hash if stored
          $info = password_get_info($user['password_hash']);
          if (!empty($info['algo'])) {
            $ok = password_verify($password, $user['password_hash']);
            error_log("--- PASSWORD_VERIFY RESULT ---");
            error_log("Using password_verify - Result: " . ($ok ? 'SUCCESS' : 'FAILED'));
          } else {
            // Legacy: stored as plaintext in password_hash column
            // Test multiple comparison methods
            error_log("--- PLAIN TEXT COMPARISON METHODS ---");
            
            // Method 1: Exact comparison
            $method1 = ($user['password_hash'] === $password);
            error_log("Exact comparison (===): " . ($method1 ? 'MATCH' : 'NO MATCH'));
            
            // Method 2: Trimmed comparison
            $stored_clean = trim($user['password_hash']);
            $input_clean = trim($password);
            $method2 = ($stored_clean === $input_clean);
            error_log("Trimmed comparison: " . ($method2 ? 'MATCH' : 'NO MATCH'));
            error_log("Stored trimmed: '" . $stored_clean . "'");
            error_log("Input trimmed: '" . $input_clean . "'");
            
            // Method 3: Case-insensitive
            $method3 = (strcasecmp($stored_clean, $input_clean) === 0);
            error_log("Case-insensitive comparison: " . ($method3 ? 'MATCH' : 'NO MATCH'));
            
            // Method 4: MD5 comparison (if someone stored MD5 hashes)
            $method4 = (md5($password) === $user['password_hash']);
            error_log("MD5 comparison: " . ($method4 ? 'MATCH' : 'NO MATCH'));
            
            $ok = $method1 || $method2 || $method3 || $method4;
            error_log("FINAL PLAIN TEXT RESULT: " . ($ok ? 'SUCCESS' : 'FAILED'));
          }
        }

        error_log("=== LOGIN DEBUG END ===");

        if ($ok) {
          $_SESSION['committee_id']          = (int)$user['id'];
          $_SESSION['committee_username']    = (string)$user['username'];
          $_SESSION['committee_name']        = (string)$user['name'];
          $_SESSION['committee_can_all']     = (int)$user['can_view_all'] === 1;
          $_SESSION['committee_college_id']  = isset($user['college_id']) ? (int)$user['college_id'] : null;
          
          // Store the role in session for redirection
          $_SESSION['user_role'] = $role;

          // REMOVED: last_login update since column doesn't exist
          // if ($upd = $mysqli1->prepare("UPDATE committee_users SET last_login=NOW() WHERE id=?")) {
          //   $upd->bind_param("i", $_SESSION['committee_id']);
          //   $upd->execute();
          //   $upd->close();
          // }

          // Redirect based on role
          switch($role) {
            case 'accountant':
              header("Location: accountant_dashboard.php");
              exit;
            case 'card_printing':
              header("Location: card_printing_dashboard.php");
              exit;
            case 'committee':
            default:
              header("Location: committee_dashboard.php");
              exit;
          }
        } else {
          $error = 'Invalid credentials.';
          if ($DEBUG) {
            $error .= ' Check server error logs for detailed debugging information.';
          }
        }
      }
    }
  } catch (Throwable $e) {
    error_log("[committee_login][EXC] ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
    $error = $DEBUG ? ('Exception: '.$e->getMessage()) : 'Server error.';
  }
}

/* ===== Page Title Based on Role ===== */
$page_titles = [
  'committee' => 'مسجل الكلية',
  'card_printing' => 'طباعة البطاقات', 
  'accountant' => 'المحاسب'
];

$page_title = $page_titles[$role] ?? 'مسجل الكلية';

/* ===== Page ===== */
include 'header.php';
?>

<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  body, h1,h2,h3,h4,h5,h6, p, a, button, label {
    font-family: 'Cairo', system-ui, -apple-system, sans-serif !important;
  }
  .btn-dark-green { background-color:#006400; border-color:#006400; color:#fff; }
  .btn-dark-green:hover { background-color:#004d00; border-color:#004d00; }
  
  /* Role-specific button colors */
  .btn-accountant { background-color:#27ae60; border-color:#27ae60; color:#fff; }
  .btn-accountant:hover { background-color:#219653; border-color:#219653; }
  
  .btn-card-printing { background-color:#f39c12; border-color:#f39c12; color:#fff; }
  .btn-card-printing:hover { background-color:#e67e22; border-color:#e67e22; }
</style>

<div class="container-fluid bg-light min-vh-100 d-flex flex-column justify-content-center align-items-center">

  <!-- Header Image Card -->
  <div class="col-12 col-md-10 col-lg-8 col-xl-6 mb-4">
    <div class="card border-0 shadow-sm overflow-hidden rounded-4">
      <img src="img/banar2.jpg" class="img-fluid w-100" alt="Committee Banner" style="max-height: 300px; object-fit: cover;">
    </div>
  </div>

  <!-- Login Card -->
  <div class="col-12 col-md-10 col-lg-8 col-xl-6">
    <div class="card p-5 shadow-lg rounded-4">
      <h3 class="mb-4 text-center fw-bold"><?= e($page_title) ?></h3>

      <?php if ($error): ?>
        <div class="alert alert-danger text-center fs-5"><?= e($error) ?></div>
      <?php endif; ?>

      <?php if ($DEBUG): ?>
      <div class="alert alert-info">
        <h6>Debug Mode Active</h6>
        <p class="mb-1">Check your server error logs for comprehensive login debugging.</p>
        <p class="mb-1">Session ID: <?= session_id() ?></p>
        <p class="mb-1">Username attempted: <?= e($username) ?></p>
        <p class="mb-0">Current Role: <?= e($role) ?></p>
      </div>
      <?php endif; ?>

      <form method="post" class="row g-4" action="committee_login.php?role=<?= e($role) ?><?= $DEBUG ? '&debug=1':'' ?>">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

        <div class="form-floating">
          <input type="text"
                 class="form-control form-control-lg"
                 id="username" name="username"
                 placeholder="Username" required
                 value="<?= e($username) ?>">
          <label for="username" class="fs-6">Username</label>
        </div>

        <div class="form-floating">
          <input type="password"
                 class="form-control form-control-lg"
                 id="password" name="password"
                 placeholder="Password" required>
          <label for="password" class="fs-6">Password</label>
        </div>

        <?php if ($role === 'accountant'): ?>
          <button class="btn btn-accountant w-100 py-3 fs-5" type="submit">Login as Accountant</button>
        <?php elseif ($role === 'card_printing'): ?>
          <button class="btn btn-card-printing w-100 py-3 fs-5" type="submit">Login for Card Printing</button>
        <?php else: ?>
          <button class="btn btn-dark-green w-100 py-3 fs-5" type="submit">Login</button>
        <?php endif; ?>
      </form>
    </div>
  </div>

</div>

<?php include 'footer.php'; ?>