<?php
// ============================================================
//  HealthLink – Patient Login
//  File: login.php
// ============================================================
require_once 'config.php';

if (!empty($_SESSION['patient_id'])) {
    header('Location: ' . SITE_URL . '/patient/dashboard.php');
    exit;
}

$errors = [];
$email  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = clean($_POST['email']    ?? '');
    $password = $_POST['password']        ?? '';

    if (empty($email))    $errors[] = 'Email address dalo.';
    if (empty($password)) $errors[] = 'Password dalo.';

    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT id, full_name, password, is_active, email_verified FROM patients WHERE email = ?");
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $errors[] = 'Yeh email registered nahi hai.';
        } else {
            $patient = $result->fetch_assoc();

            if (!password_verify($password, $patient['password'])) {
                $errors[] = 'Password galat hai.';
            } elseif (!$patient['is_active']) {
                $errors[] = 'Aapka account suspend ho gaya hai. Support se rabta karo.';
            } else {
                // ✅ Login success
                $_SESSION['patient_id']   = $patient['id'];
                $_SESSION['patient_name'] = $patient['full_name'];

                // Last login update
                $conn->query("UPDATE patients SET last_login = NOW() WHERE id = {$patient['id']}");

                // Audit log
                $action = 'patient_login';
                $ip     = $_SERVER['REMOTE_ADDR'] ?? '';
                $log    = $conn->prepare("INSERT INTO audit_logs (user_type,user_id,action,ip_address) VALUES ('patient',?,?,?)");
                $log->bind_param('iss', $patient['id'], $action, $ip);
                $log->execute();

                $redirect = $_GET['redirect'] ?? SITE_URL . '/patient/dashboard.php';
                header('Location: ' . $redirect);
                exit;
            }
        }
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
  <title>Login – HealthLink</title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    *, *::before, *::after { box-sizing:border-box; margin:0; padding:0; }
    :root {
      --teal:       #0B7B6E;
      --teal-light: #13A898;
      --teal-pale:  #E6F5F3;
      --navy:       #0D2340;
      --slate:      #4A5568;
      --border:     #D4E8E5;
      --bg:         #F7FAFA;
      --red:        #e74c3c;
    }
    body { font-family:'Plus Jakarta Sans',sans-serif; background:var(--bg); color:var(--navy); min-height:100vh; display:flex; }

    .page-wrap { display:grid; grid-template-columns:1fr 1fr; width:100%; }

    /* LEFT */
    .left-panel {
      background: linear-gradient(160deg, var(--navy) 0%, #0B4A42 100%);
      padding: 60px 50px; display:flex; flex-direction:column;
      justify-content:space-between; position:relative; overflow:hidden;
    }
    .left-panel::before {
      content:''; position:absolute; width:380px; height:380px; border-radius:50%;
      background:rgba(19,168,152,0.12); top:-80px; right:-80px;
    }
    .brand { display:flex; align-items:center; gap:12px; text-decoration:none; z-index:1; }
    .brand-icon { width:44px; height:44px; border-radius:12px; background:linear-gradient(135deg,var(--teal),var(--teal-light)); display:flex; align-items:center; justify-content:center; font-size:1.4rem; }
    .brand-name  { font-size:1.4rem; font-weight:800; color:white; }
    .brand-name span { color:var(--teal-light); }

    .welcome-box { z-index:1; }
    .welcome-box h2 { font-size:2rem; font-weight:700; color:white; margin-bottom:14px; line-height:1.3; }
    .welcome-box p  { color:rgba(255,255,255,0.6); font-size:0.95rem; line-height:1.75; }

    .stats-row { display:grid; grid-template-columns:1fr 1fr; gap:14px; z-index:1; }
    .stat-box {
      background:rgba(255,255,255,0.08); border:1px solid rgba(255,255,255,0.12);
      border-radius:14px; padding:18px 20px;
    }
    .stat-box .num { font-size:1.6rem; font-weight:800; color:var(--teal-light); }
    .stat-box .lbl { font-size:0.75rem; color:rgba(255,255,255,0.5); margin-top:2px; }

    /* RIGHT */
    .right-panel {
      padding: 0; display:flex; align-items:center; justify-content:center;
    }
    .login-box { width:100%; max-width:420px; padding:40px; }
    .login-box h1 { font-size:1.8rem; font-weight:800; margin-bottom:6px; }
    .login-box .sub { color:var(--slate); font-size:0.9rem; margin-bottom:30px; }
    .login-box .sub a { color:var(--teal); text-decoration:none; font-weight:600; }

    <?php if (!empty($_SESSION['flash'])): ?>
    /* flash will show */
    <?php endif; ?>

    .error-box { background:#fdf2f2; border:1px solid #f5c6c6; border-radius:10px; padding:14px 18px; margin-bottom:20px; }
    .error-box p { color:var(--red); font-size:0.85rem; margin-bottom:4px; }
    .error-box p:last-child { margin:0; }
    .error-box p::before { content:'⚠ '; }

    .field { display:flex; flex-direction:column; gap:6px; margin-bottom:16px; }
    .field label { font-size:0.82rem; font-weight:600; color:var(--slate); }
    .field-wrap { position:relative; }
    .field input {
      width:100%; padding:12px 44px 12px 14px; border:1.5px solid var(--border);
      border-radius:9px; font-size:0.9rem; font-family:inherit; color:var(--navy);
      background:white; outline:none; transition:border 0.2s;
    }
    .field input:focus { border-color:var(--teal); box-shadow:0 0 0 3px var(--teal-pale); }
    .toggle-pw {
      position:absolute; right:12px; top:50%; transform:translateY(-50%);
      background:none; border:none; cursor:pointer; font-size:1.1rem; color:var(--slate);
    }

    .forgot { text-align:right; margin-top:-8px; margin-bottom:20px; }
    .forgot a { font-size:0.82rem; color:var(--teal); text-decoration:none; font-weight:600; }

    .btn-submit {
      width:100%; padding:13px; background:var(--teal); color:white;
      border:none; border-radius:10px; font-size:1rem; font-weight:700;
      cursor:pointer; font-family:inherit; transition:all 0.2s; margin-bottom:20px;
    }
    .btn-submit:hover { background:var(--teal-light); transform:translateY(-1px); }

    .divider { display:flex; align-items:center; gap:12px; margin-bottom:20px; }
    .divider hr { flex:1; border:none; border-top:1px solid var(--border); }
    .divider span { font-size:0.78rem; color:var(--slate); }

    .btn-doctor {
      display:block; width:100%; padding:12px; border:1.5px solid var(--border);
      border-radius:10px; text-align:center; font-size:0.9rem; font-weight:600;
      color:var(--navy); text-decoration:none; transition:all 0.2s;
    }
    .btn-doctor:hover { border-color:var(--teal); color:var(--teal); background:var(--teal-pale); }

    .security-note {
      margin-top:24px; background:var(--teal-pale); border-radius:10px;
      padding:12px 16px; font-size:0.78rem; color:var(--slate);
      display:flex; align-items:center; gap:8px;
    }

    @media(max-width:800px) {
      .page-wrap { grid-template-columns:1fr; }
      .left-panel { display:none; }
      .right-panel { padding:40px 24px; }
      .login-box { padding:0; max-width:100%; }
    }
  </style>
</head>
<body>
<div class="page-wrap">

  <!-- LEFT -->
  <div class="left-panel">
    <a href="<?= SITE_URL ?>" class="brand">
      <div class="brand-icon">➕</div>
      <span class="brand-name">Health<span>Link</span></span>
    </a>

    <div class="welcome-box">
      <h2>Wapas Aaiye!<br>Aapki Health<br>Aapka Control</h2>
      <p>Login karein aur apni medical records, appointments, aur consultations access karein.</p>
    </div>

    <div class="stats-row">
      <div class="stat-box"><div class="num">500+</div><div class="lbl">Verified Doctors</div></div>
      <div class="stat-box"><div class="num">24/7</div><div class="lbl">Online Support</div></div>
      <div class="stat-box"><div class="num">50K+</div><div class="lbl">Patients</div></div>
      <div class="stat-box"><div class="num">🔒</div><div class="lbl">100% Secure</div></div>
    </div>
  </div>

  <!-- RIGHT -->
  <div class="right-panel">
    <div class="login-box">
      <h1>Patient Login</h1>
      <p class="sub">Account nahi hai? <a href="<?= SITE_URL ?>/register.php">Free mein banao →</a></p>

      <?php showFlash(); ?>

      <?php if (!empty($errors)): ?>
        <div class="error-box">
          <?php foreach ($errors as $err): ?>
            <p><?= htmlspecialchars($err) ?></p>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <form method="POST">
        <div class="field">
          <label>Email Address</label>
          <div class="field-wrap">
            <input type="email" name="email" placeholder="aap@email.com"
                   value="<?= htmlspecialchars($email) ?>" required autocomplete="email">
          </div>
        </div>

        <div class="field">
          <label>Password</label>
          <div class="field-wrap">
            <input type="password" name="password" id="pw" placeholder="Apna password dalo" required autocomplete="current-password">
            <button type="button" class="toggle-pw" id="togglePw" aria-label="Show password">👁</button>
          </div>
        </div>

        <div class="forgot">
          <a href="<?= SITE_URL ?>/forgot-password.php">Password bhool gaye?</a>
        </div>

        <button type="submit" class="btn-submit">🔐 Login Karein</button>
      </form>

      <div class="divider"><hr><span>ya phir</span><hr></div>

      <a href="<?= SITE_URL ?>/doctor-login.php" class="btn-doctor">🩺 Doctor Login</a>

      <div class="security-note">
        🔒 Aapka data SSL encryption se secure hai. HealthLink kabhi bhi aapka password nahi maangta email ya SMS pe.
      </div>
    </div>
  </div>

</div>
<script>
  const pw = document.getElementById('pw');
  const toggle = document.getElementById('togglePw');
  toggle.addEventListener('click', () => {
    if (pw.type === 'password') { pw.type = 'text'; toggle.textContent = '🙈'; }
    else                        { pw.type = 'password'; toggle.textContent = '👁'; }
  });
</script>
</body>
</html>