<?php


session_start();

const DEBUG_REASON = true; // set false in production

require_once __DIR__ . '/config.php'; // must define PDO in $dbh or $conn

// ---- Normalize PDO handle regardless of variable name in config.php ----
$pdo = null;
if (isset($conn) && $conn instanceof PDO) { $pdo = $conn; }
elseif (isset($dbh) && $dbh instanceof PDO) { $pdo = $dbh; }

if (!$pdo) {
  fail('DB not connected — ensure config.php creates $conn or $dbh as PDO.');
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// ---- CSRF ----
if (empty($_SESSION['csrf'])) {
  $_SESSION['csrf'] = bin2hex(random_bytes(32));
}
function csrf_ok(string $t): bool { return hash_equals($_SESSION['csrf'] ?? '', $t); }
function fail(string $msg){
  if (DEBUG_REASON) { echo "<!doctype html><meta charset='utf-8'><script>alert(".json_encode($msg).");history.back();</script>"; }
  else { echo "<!doctype html><meta charset='utf-8'><script>alert('Login failed');history.back();</script>"; }
  exit;
}

// ---- Handle POST ----
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim((string)($_POST['email'] ?? ''));
  $pwd   = (string)($_POST['password'] ?? '');
  $pin   = (string)($_POST['pin'] ?? '');
  $csrf  = (string)($_POST['csrf'] ?? '');

  if (!csrf_ok($csrf)) {
    $error = 'Session expired. Refresh and try again.';
  } elseif ($email === '' || $pwd === '' || $pin === '') {
    $error = 'All fields are required.';
  } else {
    try {
      // Case-insensitive match for email (avoids subtle collation issues)
      $sql = "SELECT
                id, email, password, pin,
                username, empId, userRole, userDepartment, profile_pic, status, email_confirmed
              FROM emplist
              WHERE LOWER(email) = LOWER(:email)
              LIMIT 1";
      $st = $pdo->prepare($sql);
      $st->execute([':email' => $email]);
      $user = $st->fetch(PDO::FETCH_ASSOC);

      if (!$user) {
        $error = 'Invalid email, password, or PIN.';
      } else {
        // Optional status check
        if (!empty($user['status']) && strtolower((string)$user['status']) !== 'active') {
          $error = 'Your account is not active.';
        }

        // Trim right-side spaces (very common)
        $dbPwd = rtrim((string)$user['password']);
        $dbPin = rtrim((string)$user['pin']);
        $inPwd = rtrim($pwd);
        $inPin = rtrim($pin);

        // Password: support hashed → md5 → plaintext
        $okPwd = false;
        $info  = password_get_info($dbPwd);
        if (!empty($info['algo'])) {
          $okPwd = password_verify($inPwd, $dbPwd);
        }
        if (!$okPwd && strlen($dbPwd) === 32) { // legacy md5
          $okPwd = hash_equals($dbPwd, md5($inPwd));
        }
        if (!$okPwd) { // plaintext fallback
          $okPwd = hash_equals($dbPwd, $inPwd);
        }

        // PIN: compare as strings; keep leading zeros intact
        $okPin = hash_equals($dbPin, $inPin);

        if (!$error && $okPwd && $okPin) {
          // Success → set session (and unify keys used across the app)
          session_regenerate_id(true);

          // Canonical: use EMAIL in clogin so profile/dashboard code finds the same user
          $_SESSION['alogin']   = $user['email'];                 // keep your original key for compatibility
          $_SESSION['admin_id'] = (int)$user['id'];
          $_SESSION['role']     = $user['userRole'] ?: 'ADMIN';   // preserve/override as needed

          // Keys your other pages expect:
          $_SESSION['clogin'] = $user['email'];
          $_SESSION['cemail'] = $user['email'];
          $_SESSION['cname']  = $user['username'] ?: 'Admin';
          $_SESSION['empId']  = $user['empId'] ?? '';

          // Warm a minimal cached user object (handy for headers/menus)
          $_SESSION['me'] = [
            'id'             => (int)$user['id'],
            'empId'          => (string)($user['empId'] ?? ''),
            'username'       => (string)($user['username'] ?? ''),
            'email'          => (string)$user['email'],
            'userRole'       => (string)($user['userRole'] ?? ''),
            'userDepartment' => (string)($user['userDepartment'] ?? ''),
            'profile_pic'    => (string)($user['profile_pic'] ?? ''),
          ];

          header('Location: dashboard.php'); // or profile.php
          exit;
        } else if (!$error) {
          $error = 'Invalid email, password, or PIN.';
        }
      }
    } catch (Throwable $e) {
      $error = 'Server error: '.$e->getMessage();
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
<style>
  :root{ --brand1:#0d6efd; --brand2:#6f42c1; --ink:#111827; --muted:#6b7280; --card:#ffffff; }
  body{min-height:100vh;display:flex;align-items:center;justify-content:center;background:
    -colo, rgba(13,110,253,.18), transparent),
    radial-gradient(1200px 600px at 90% 90%, rgba(111,66,193,.18), transparent),
    linear-gradient(135deg, #eef2ff, #f7f7ff);
    font-family: Inter, Segoe UI, system-ui, -apple-system, Arial, sans-serif;}
  .auth-wrap{width:100%;max-width:980px;padding:24px}
  .brand-pane{background-color:#F28C28;color:#fff;border-radius:24px;padding:36px;position:relative;overflow:hidden;box-shadow:0 20px 50px rgba(13,110,253,.20);}
  .brand-pane .badge{background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.25);backdrop-filter:blur(6px)}
  .bubble{position:absolute;border-radius:50%;filter:blur(20px);opacity:.55;pointer-events:none}
  .bubble.b1{width:180px;height:180px;right:-40px;top:-40px;background:rgba(255,255,255,.25)}
  .bubble.b2{width:120px;height:120px;left:-20px;bottom:-20px;background:rgba(255,255,255,.18)}
  .card-pane{background:rgba(255,255,255,.75);backdrop-filter:blur(8px);border:1px solid rgba(13,110,253,.08);border-radius:24px;box-shadow:0 30px 60px rgba(0,0,0,.08)}
  .form-control{border-radius:14px!important;padding:.85rem 1rem}
  .input-group-text{border-radius:14px 0 0 14px!important}
  .btn-auth{border-radius:14px;padding:.9rem;font-weight:700;box-shadow:0 10px 20px rgba(13,110,253,.25)}
  .small-note{color:var(--muted)}
  .logo-circle{width:68px;height:68px;border-radius:50%;background:linear-gradient(135deg,#fff,#e9eeff);display:flex;align-items:center;justify-content:center;color:var(--brand1);font-size:26px;box-shadow:0 8px 24px rgba(0,0,0,.08)}
  .brand-title{font-weight:800;letter-spacing:.25px}
  .divider{text-align:center;margin:18px 0;color:#9aa3b2}
  .divider:before,.divider:after{content:"";display:inline-block;width:35%;height:1px;background:#e5e7eb;vertical-align:middle;margin:0 10px}
</style>
</head>
<body>
  <div class="auth-wrap" >
    <div class="row g-4 align-items-stretch">
<div class="col-lg-6">
  <div class="brand-pane h-100 p-4 position-relative text-white rounded-4 shadow-lg"
       style="background: linear-gradient(135deg, #ff7a00 0%, #ffb266 100%); overflow:hidden;">
    
    <!-- Top Branding -->
    <div class="d-flex align-items-center gap-3 mb-4">
      <div class="logo-circle bg-white text-orange-600 d-flex align-items-center justify-content-center rounded-circle shadow"
           style="width:3rem; height:3rem;">
        <i class="fa-solid fa-shield-halved fs-5"></i>
      </div>
      <div>
        <div class="brand-title h3 fw-bold mb-0">Admin Console</div>
        <div class="small text-white-75">Centralized Management & Security</div>
      </div>
    </div>

    <!-- Highlights -->
    <div class="mt-3 mb-4">
      <span class="badge bg-white text-black rounded-pill px-3 py-2 shadow-sm me-2">
        <i class="fa-solid fa-lock me-1"></i> Encrypted Access
      </span>
      <span class="badge bg-white text-black rounded-pill px-3 py-2 shadow-sm">
        <i class="fa-solid fa-gauge-high me-1"></i> High Performance
      </span>
    </div>

    <hr class="border-light border-opacity-25 my-4">

    <!-- Feature List -->
    <ul class="list-unstyled m-0">
      <li class="d-flex gap-3 align-items-start mb-3">
        <i class="fa-regular fa-circle-check mt-1"></i>
        <div>
          <div class="fw-semibold">Role-Based Access</div>
          <div class="text-white-75 small">Control permissions for admins, staff, and users.</div>
        </div>
      </li>
      <li class="d-flex gap-3 align-items-start mb-3">
        <i class="fa-regular fa-circle-check mt-1"></i>
        <div>
          <div class="fw-semibold">Real-Time Monitoring</div>
          <div class="text-white-75 small">Track user activity, logins, and security alerts instantly.</div>
        </div>
      </li>
      <li class="d-flex gap-3 align-items-start mb-3">
        <i class="fa-regular fa-circle-check mt-1"></i>
        <div>
          <div class="fw-semibold">User & Group Management</div>
          <div class="text-white-75 small">Add, update, or suspend accounts easily.</div>
        </div>
      </li>
      <li class="d-flex gap-3 align-items-start mb-3">
        <i class="fa-regular fa-circle-check mt-1"></i>
        <div>
          <div class="fw-semibold">Reporting & Analytics</div>
          <div class="text-white-75 small">Generate reports on usage, performance, and KPIs.</div>
        </div>
      </li>
      <li class="d-flex gap-3 align-items-start">
        <i class="fa-regular fa-circle-check mt-1"></i>
        <div>
          <div class="fw-semibold">24×7 Availability</div>
          <div class="text-white-75 small">Optimized for desktop, tablet, and mobile devices.</div>
        </div>
      </li>
    </ul>

    <!-- Background Bubbles -->
    <div class="bubble position-absolute rounded-circle bg-white opacity-25" 
         style="width:120px; height:120px; bottom:-40px; right:-40px;"></div>
    <div class="bubble position-absolute rounded-circle bg-white opacity-10" 
         style="width:200px; height:200px; top:-60px; left:-60px;"></div>
  </div>
</div>

      <div class="col-lg-6">
        <div class="card-pane p-4 p-md-5 h-100 d-flex">
          <div class="w-100 d-flex flex-column">
            <div class="mb-3">
              <div class="text-center mb-4">
  <img src="https://test.traderssolution.com/adminvideonew/demo.png" alt="Company Logo" 
       style="max-height:60px; width:auto;" class="mb-2">
 
</div>
              <div class="small-note">Use your admin email, password and PIN</div>
            </div>

            <?php if (!empty($error)): ?>
              <div class="alert alert-danger" role="alert"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

            <form method="post" class="mt-2" novalidate>
              <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8') ?>">

              <div class="mb-3">
                <label class="form-label">Email</label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fa-regular fa-envelope"></i></span>
                  <input type="email" name="email" class="form-control" placeholder="admin@example.com" required>
                </div>
              </div>

              <div class="mb-3">
                <label class="form-label d-flex justify-content-between">
                  <span>Password</span>
                  <a href="#" class="small text-decoration-none" onclick="event.preventDefault();toggleVis('password','btnPw');">Show/Hide</a>
                </label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fa-solid fa-lock"></i></span>
                  <input type="password" id="password" name="password" class="form-control" placeholder="••••••••" required>
                  <button type="button" class="btn btn-outline-secondary" id="btnPw" onclick="toggleVis('password','btnPw')">
                    <i class="fa-regular fa-eye"></i>
                  </button>
                </div>
              </div>

              <div class="mb-2">
                <label class="form-label d-flex justify-content-between">
                  <span>PIN</span>
                  <a href="#" class="small text-decoration-none" onclick="event.preventDefault();toggleVis('pin','btnPin');">Show/Hide</a>
                </label>
                <div class="input-group">
                  <span class="input-group-text"><i class="fa-solid fa-key"></i></span>
                  <input type="password" id="pin" name="pin" class="form-control" placeholder="6-digit PIN" inputmode="numeric" maxlength="6" required>
                  <button type="button" class="btn btn-outline-secondary" id="btnPin" onclick="toggleVis('pin','btnPin')">
                    <i class="fa-regular fa-eye"></i>
                  </button>
                </div>
                <div class="form-text">Enter your security PIN (e.g., 123456)</div>
              </div>

              <button class="btn btn-primary w-100 btn-auth mt-3" type="submit" style="background-color:#F28C28;">
                <i class="fa-solid fa-right-to-bracket me-1"></i> Login
              </button>

              <div class="divider">or</div>
              <div class="text-center small-note">Need access? Contact the system administrator.</div>
            </form>

            <div class="mt-auto text-center small text-muted pt-3">
              © <?= date('Y') ?> Demo Markets— All rights reserved
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleVis(inputId, btnId){
  const input = document.getElementById(inputId);
  const btn   = document.getElementById(btnId);
  if (!input || !btn) return;
  const isPwd = input.type === 'password';
  input.type = isPwd ? 'text' : 'password';
  btn.innerHTML = isPwd ? '<i class="fa-regular fa-eye-slash"></i>' : '<i class="fa-regular fa-eye"></i>';
}
</script>
</body>
</html>
