<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "config.php";
include_once "../includes/notify_lib.php";

if (!isset($_SESSION['pending_login_user_id'])) {
    header('Location: index');
    exit;
}
$userId = (int)$_SESSION['pending_login_user_id'];

$userRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id, name, email, mobile FROM users WHERE id = $userId"));
if (!$userRow) {
    header('Location: index');
    exit;
}

$message = '';
$messageType = 'error';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_otp'])) {
    $result = verify_email_otp($conn, $userId, $_POST['otp'] ?? '', 'login');
    if ($result['ok']) {
        $remember = !empty($_SESSION['pending_login_remember']);
        unset($_SESSION['pending_login_user_id'], $_SESSION['pending_login_remember']);

        // Stay logged in until the user manually logs out (Amazon-style).
        $params = session_get_cookie_params();
        setcookie(session_name(), session_id(), time() + (365 * 24 * 60 * 60), $params["path"], $params["domain"], $params["secure"], $params["httponly"]);

        $_SESSION["username"] = $userRow['mobile'];
        $_SESSION["user_id"] = $userId;
        mysqli_query($conn, "UPDATE users SET acc_lock = 0 WHERE id = $userId");

        if (!empty($userRow['email'])) {
            send_login_alert($conn, $userId, $userRow['email'], $userRow['name'] ?? $userRow['mobile']);
        }

        echo '<script>window.location.href = "dashboard";</script>';
        exit;
    }
    $message = $result['message'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_otp'])) {
    $result = issue_email_otp($conn, $userId, $userRow['email'], $userRow['name'] ?? $userRow['mobile'], 'login');
    $message = $result['ok'] ? 'Naya code bhej diya gaya hai.' : $result['message'];
    $messageType = $result['ok'] ? 'success' : 'error';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Verify Login</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
    *{box-sizing:border-box}
    body{margin:0;font-family:'Inter',sans-serif;min-height:100vh;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);display:flex;align-items:center;justify-content:center;padding:20px;color:#fff}
    .card{background:rgba(255,255,255,.06);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.12);border-radius:24px;padding:40px 36px;width:100%;max-width:420px;box-shadow:0 30px 80px rgba(0,0,0,.4);text-align:center}
    .icon{width:60px;height:60px;border-radius:16px;background:linear-gradient(135deg,#6c63ff,#e040fb);display:inline-flex;align-items:center;justify-content:center;font-size:26px;margin-bottom:18px}
    h1{font-size:1.3rem;margin:0 0 8px}
    p{color:rgba(255,255,255,.55);font-size:.88rem;line-height:1.6;margin:0 0 22px}
    p b{color:#fff}
    input.otp{width:100%;background:rgba(255,255,255,.06);border:1.5px solid rgba(255,255,255,.15);border-radius:12px;padding:16px;color:#fff;font-size:1.6rem;text-align:center;letter-spacing:10px;font-weight:700;margin-bottom:16px}
    input.otp:focus{outline:none;border-color:#6c63ff}
    button{width:100%;border:none;border-radius:12px;padding:14px;font-weight:700;font-size:.95rem;cursor:pointer}
    .btn-verify{background:linear-gradient(135deg,#6c63ff,#e040fb);color:#fff;margin-bottom:12px}
    .btn-resend{background:rgba(255,255,255,.08);color:#fff}
    .msg{border-radius:10px;padding:10px 14px;font-size:.82rem;margin-bottom:16px;text-align:left}
    .msg.error{background:rgba(255,101,132,.12);color:#ff6584}
    .msg.success{background:rgba(67,233,123,.12);color:#43e97b}
</style>
</head>
<body>
<div class="card">
    <div class="icon">🔐</div>
    <h1>Verify It's You</h1>
    <p>Login complete karne ke liye <b><?php echo htmlspecialchars($userRow['email']); ?></b> par bheja gaya code daalein.</p>

    <?php if ($message): ?><div class="msg <?php echo $messageType; ?>"><?php echo htmlspecialchars($message); ?></div><?php endif; ?>

    <form method="POST" action="">
        <input type="text" name="otp" class="otp" maxlength="6" inputmode="numeric" placeholder="------" autofocus required>
        <button type="submit" name="verify_otp" class="btn-verify">Verify &amp; Login</button>
    </form>
    <form method="POST" action="">
        <button type="submit" name="resend_otp" class="btn-resend">Resend Code</button>
    </form>
</div>
</body>
</html>
