<?php
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/includes/functions.php';
startSession();
if (!isLoggedIn()) { header('Location: ' . BASE_URL . '/index.php'); exit; }

$user    = currentUser();
$forced  = !empty($_SESSION['must_change_password']);
$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $current = $_POST['current_password'] ?? '';
    $new     = $_POST['new_password']     ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    // Validate
    if (!$current || !$new || !$confirm) {
        $error = 'All fields are required.';
    } elseif ($new !== $confirm) {
        $error = 'New password and confirm password do not match.';
    } elseif (strlen($new) < 8) {
        $error = 'New password must be at least 8 characters.';
    } elseif (!preg_match('/[A-Z]/', $new) || !preg_match('/[0-9]/', $new)) {
        $error = 'Password must contain at least one uppercase letter and one number.';
    } else {
        $db      = Database::getInstance();
        $dbUser  = $db->fetchOne("SELECT password_hash FROM users WHERE id = ?", [$user['id']]);

        if (!$dbUser || !password_verify($current, $dbUser['password_hash'])) {
            $error = 'Current password is incorrect.';
        } else {
            $newHash = password_hash($new, PASSWORD_BCRYPT, ['cost' => 12]);
            $db->execute(
                "UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?",
                [$newHash, $user['id']]
            );
            $_SESSION['must_change_password'] = false;
            setFlash('success', 'Password changed successfully.');
            header('Location: ' . BASE_URL . '/dashboard.php');
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Change Password – <?= APP_NAME ?></title>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@2.44.0/tabler-icons.min.css">
<style>
  body { background: linear-gradient(135deg, #1a5f7a 0%, #0d3d50 100%); min-height:100vh; display:flex; align-items:center; justify-content:center; }
  .card { border-radius:16px; padding:40px; width:100%; max-width:460px; box-shadow:0 20px 60px rgba(0,0,0,.3); }
  .logo { width:60px; height:60px; background:#f0a500; border-radius:14px; display:flex; align-items:center; justify-content:center; font-size:24px; font-weight:800; color:#fff; margin:0 auto 16px; }
  .form-control:focus { border-color:#1a5f7a; box-shadow:0 0 0 .2rem rgba(26,95,122,.2); }
  .btn-primary { background:#1a5f7a; border:none; padding:12px; font-size:15px; font-weight:600; border-radius:8px; }
  .btn-primary:hover { background:#2d8baa; }
  .strength-bar { height:5px; border-radius:3px; transition:all .3s; }
  .req { font-size:0.78rem; }
  .req .ok  { color:#198754; }
  .req .bad { color:#adb5bd; }
</style>
</head>
<body>
<div class="card bg-white">
  <div class="logo">HR</div>
  <h4 class="text-center fw-bold mb-1">
    <?= $forced ? 'Set Your New Password' : 'Change Password' ?>
  </h4>
  <?php if ($forced): ?>
    <div class="alert alert-warning py-2 small text-center mb-3">
      <i class="ti ti-lock-exclamation me-1"></i>
      You must change your password before continuing.
    </div>
  <?php else: ?>
    <p class="text-center text-muted small mb-4">Hello, <?= htmlspecialchars($user['name']) ?></p>
  <?php endif; ?>

  <?php if ($error): ?>
    <div class="alert alert-danger py-2 small"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <form method="POST">
    <?= csrfField() ?>
    <div class="mb-3">
      <label class="form-label fw-semibold small">Current Password</label>
      <div class="input-group">
        <span class="input-group-text"><i class="ti ti-lock"></i></span>
        <input type="password" name="current_password" id="curPwd" class="form-control" placeholder="Enter current password" required>
        <button type="button" class="btn btn-outline-secondary" onclick="toggleField('curPwd','curIcon')"><i class="ti ti-eye" id="curIcon"></i></button>
      </div>
      <?php if ($forced): ?>
        <div class="form-text">Default password: <code>Gmhpl_2025</code></div>
      <?php endif; ?>
    </div>

    <div class="mb-3">
      <label class="form-label fw-semibold small">New Password</label>
      <div class="input-group">
        <span class="input-group-text"><i class="ti ti-lock-open"></i></span>
        <input type="password" name="new_password" id="newPwd" class="form-control" placeholder="Enter new password" oninput="checkStrength()" required>
        <button type="button" class="btn btn-outline-secondary" onclick="toggleField('newPwd','newIcon')"><i class="ti ti-eye" id="newIcon"></i></button>
      </div>
      <div class="mt-1 strength-bar bg-secondary" id="strengthBar"></div>
      <div class="req mt-2">
        <div id="reqLen"  class="bad"><i class="ti ti-circle me-1"></i>At least 8 characters</div>
        <div id="reqUpper"class="bad"><i class="ti ti-circle me-1"></i>At least one uppercase letter (A–Z)</div>
        <div id="reqNum"  class="bad"><i class="ti ti-circle me-1"></i>At least one number (0–9)</div>
      </div>
    </div>

    <div class="mb-4">
      <label class="form-label fw-semibold small">Confirm New Password</label>
      <div class="input-group">
        <span class="input-group-text"><i class="ti ti-lock-check"></i></span>
        <input type="password" name="confirm_password" id="conPwd" class="form-control" placeholder="Re-enter new password" oninput="checkMatch()" required>
        <button type="button" class="btn btn-outline-secondary" onclick="toggleField('conPwd','conIcon')"><i class="ti ti-eye" id="conIcon"></i></button>
      </div>
      <div class="req mt-1" id="matchMsg" style="display:none"></div>
    </div>

    <button type="submit" class="btn btn-primary w-100">
      <i class="ti ti-key me-2"></i>Change Password
    </button>
    <?php if (!$forced): ?>
      <a href="<?= BASE_URL ?>/dashboard.php" class="btn btn-outline-secondary w-100 mt-2">Cancel</a>
    <?php endif; ?>
  </form>
</div>
<script>
function toggleField(id, iconId) {
  const inp = document.getElementById(id);
  const ico = document.getElementById(iconId);
  if (inp.type === 'password') { inp.type = 'text'; ico.className = 'ti ti-eye-off'; }
  else                         { inp.type = 'password'; ico.className = 'ti ti-eye'; }
}

function checkStrength() {
  const pwd = document.getElementById('newPwd').value;
  const hasLen   = pwd.length >= 8;
  const hasUpper = /[A-Z]/.test(pwd);
  const hasNum   = /[0-9]/.test(pwd);

  setReq('reqLen',   hasLen);
  setReq('reqUpper', hasUpper);
  setReq('reqNum',   hasNum);

  const score = [hasLen, hasUpper, hasNum].filter(Boolean).length;
  const bar   = document.getElementById('strengthBar');
  const colors = ['#dc3545','#fd7e14','#198754'];
  const widths = ['33%','66%','100%'];
  bar.style.background = colors[score - 1] || '#dee2e6';
  bar.style.width      = score ? widths[score - 1] : '0';
  checkMatch();
}

function setReq(id, ok) {
  const el = document.getElementById(id);
  el.className = ok ? 'ok' : 'bad';
  el.querySelector('i').className = ok ? 'ti ti-circle-check me-1' : 'ti ti-circle me-1';
}

function checkMatch() {
  const np  = document.getElementById('newPwd').value;
  const cp  = document.getElementById('conPwd').value;
  const msg = document.getElementById('matchMsg');
  if (!cp) { msg.style.display='none'; return; }
  msg.style.display = 'block';
  if (np === cp) { msg.innerHTML = '<span class="ok"><i class="ti ti-circle-check me-1"></i>Passwords match</span>'; }
  else           { msg.innerHTML = '<span style="color:#dc3545"><i class="ti ti-circle-x me-1"></i>Passwords do not match</span>'; }
}
</script>
</body>
</html>
