<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "auth/config.php";
include 'auth/function.php';
include_once 'includes/notify_lib.php';
include_once 'includes/white_label_lib.php';
block_if_white_label_domain($conn);

$step = 'email'; // 'email' -> 'reset'

if (isset($_SESSION['pending_reset_user_id'])) {
    $step = 'reset';
}

// Step 1: submit email, look up account, send OTP
if (isset($_POST['request_otp'])) {
    $email = mysqli_real_escape_string($conn, trim($_POST['email'] ?? ''));
    $fetch = "SELECT * FROM users WHERE email = '$email'";
    $res = mysqli_query($conn, $fetch);
    $row = $res ? mysqli_fetch_assoc($res) : null;

    if (!$row) {
        echo '<script>Swal.fire({title:"Not Found",text:"Is email se koi account nahi mila.",icon:"error",confirmButtonText:"Ok"}).then(()=>{window.location.href="forgot-password";});</script>';
        exit;
    }

    $_SESSION['pending_reset_user_id'] = $row['id'];
    $otpResult = issue_email_otp($conn, $row['id'], $row['email'], $row['name'] ?? 'User', 'reset');

    if ($otpResult['ok']) {
        $step = 'reset';
    } else {
        echo '<script>Swal.fire({title:"Email Failed",text:"' . addslashes($otpResult['message']) . '",icon:"error",confirmButtonText:"Ok"}).then(()=>{window.location.href="forgot-password";});</script>';
        exit;
    }
}

// Step 2: submit OTP + new password
if (isset($_POST['reset_password'])) {
    $userId = (int)($_SESSION['pending_reset_user_id'] ?? 0);
    $otp = $_POST['otp'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';

    if (!$userId) {
        echo '<script>window.location.href = "forgot-password";</script>';
        exit;
    }

    if (strlen($newPassword) < 6) {
        echo '<script>Swal.fire({title:"Too Short",text:"Password kam se kam 6 characters ka hona chahiye.",icon:"error",confirmButtonText:"Ok"});</script>';
        $step = 'reset';
    } else {
        $result = verify_email_otp($conn, $userId, $otp, 'reset');
        if ($result['ok']) {
            $hashed = password_hash($newPassword, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param("si", $hashed, $userId);
            $stmt->execute();
            unset($_SESSION['pending_reset_user_id']);

            echo '<script>Swal.fire({title:"Password Changed! 🎉",text:"Ab naye password se login karein.",icon:"success",confirmButtonText:"Go to Login"}).then(()=>{window.location.href="auth/index";});</script>';
            exit;
        } else {
            echo '<script>Swal.fire({title:"Verification Failed",text:"' . addslashes($result['message']) . '",icon:"error",confirmButtonText:"Ok"});</script>';
            $step = 'reset';
        }
    }
}

$resendMessage = '';
if (isset($_POST['resend_otp'])) {
    $userId = (int)($_SESSION['pending_reset_user_id'] ?? 0);
    if ($userId) {
        $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT email, name FROM users WHERE id = $userId"));
        if ($row) {
            $r = issue_email_otp($conn, $userId, $row['email'], $row['name'] ?? 'User', 'reset');
            $resendMessage = $r['ok'] ? 'Naya code bhej diya gaya hai.' : $r['message'];
        }
    }
    $step = 'reset';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<title><?php echo $step === 'reset' ? 'Reset Password' : 'Forgot Password'; ?> | <?php echo $site_settings['brand_name']; ?></title>
<link rel="icon" type="image/x-icon" href="common/img/favicon.png"/>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;min-height:100vh;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);display:flex;align-items:center;justify-content:center;padding:40px 20px;position:relative;overflow-x:hidden;overflow-y:auto}
.blob{position:fixed;border-radius:50%;filter:blur(80px);opacity:.25;pointer-events:none}
.b1{width:500px;height:500px;background:#6c63ff;top:-100px;left:-100px;animation:blobMove 12s ease-in-out infinite alternate}
.b2{width:400px;height:400px;background:#ff6584;bottom:-80px;right:-80px;animation:blobMove 10s ease-in-out infinite alternate-reverse}
.b3{width:300px;height:300px;background:#43e97b;top:50%;left:50%;transform:translate(-50%,-50%);animation:blobMove 8s ease-in-out infinite alternate}
@keyframes blobMove{0%{transform:scale(1) translate(0,0)}100%{transform:scale(1.15) translate(30px,20px)}}
.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:440px;position:relative;z-index:1;box-shadow:0 30px 80px rgba(0,0,0,.4)}
.logo-wrap{text-align:center;margin-bottom:20px}
.logo-wrap img{max-height:50px;object-fit:contain;filter:drop-shadow(0 4px 12px rgba(108,99,255,.4))}
.icon-badge{width:56px;height:56px;border-radius:14px;background:linear-gradient(135deg,#6c63ff,#e040fb);display:flex;align-items:center;justify-content:center;font-size:24px;margin:0 auto 18px}
.brand-name{font-size:20px;font-weight:800;color:#fff;text-align:center;margin-bottom:6px}
.brand-sub{font-size:13px;color:rgba(255,255,255,.45);text-align:center;margin-bottom:28px}
.fg{margin-bottom:18px}
.fg label{display:block;font-size:12px;font-weight:600;color:rgba(255,255,255,.6);margin-bottom:7px;text-transform:uppercase;letter-spacing:.5px}
.input-wrap{position:relative}
.input-wrap i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3);font-size:14px;pointer-events:none}
.input-wrap input{width:100%;background:rgba(255,255,255,.07);border:1.5px solid rgba(255,255,255,.1);border-radius:12px;padding:13px 14px 13px 42px;font-size:14px;color:#fff;outline:none;transition:.3s;font-family:'Inter',sans-serif;box-sizing:border-box}
.input-wrap input::placeholder{color:rgba(255,255,255,.2)}
.input-wrap input:focus{border-color:#6c63ff;background:rgba(108,99,255,.12);box-shadow:0 0 0 4px rgba(108,99,255,.15)}
.otp-input{text-align:center;font-size:22px;letter-spacing:8px;font-weight:700;padding-left:14px !important}
.btn-main{width:100%;padding:14px;background:linear-gradient(135deg,#6c63ff,#e040fb);border:none;border-radius:12px;font-size:15px;font-weight:700;color:#fff;cursor:pointer;transition:.3s;font-family:'Inter',sans-serif;letter-spacing:.3px;margin-bottom:12px}
.btn-main:hover{transform:translateY(-2px);box-shadow:0 10px 30px rgba(108,99,255,.4)}
.btn-secondary{width:100%;padding:13px;background:rgba(255,255,255,.07);border:1.5px solid rgba(255,255,255,.12);border-radius:12px;font-size:14px;font-weight:600;color:#fff;cursor:pointer;font-family:'Inter',sans-serif}
.info-msg{background:rgba(108,99,255,.12);border:1px solid rgba(108,99,255,.25);color:#c7c3ff;font-size:12.5px;border-radius:10px;padding:10px 14px;margin-bottom:18px}
.login-link{text-align:center;font-size:13px;color:rgba(255,255,255,.4);margin-top:20px}
.login-link a{color:#6c63ff;text-decoration:none;font-weight:600}
.login-link a:hover{text-decoration:underline}
</style>
</head>
<body>
<div class="blob b1"></div>
<div class="blob b2"></div>
<div class="blob b3"></div>

<div class="card">
    <div class="logo-wrap">
        <img src="<?php echo $site_settings['logo_url']; ?>" alt="Logo" onerror="this.style.display='none'">
    </div>
    <div class="icon-badge"><?php echo $step === 'reset' ? '🔑' : '🔒'; ?></div>
    <div class="brand-name"><?php echo $step === 'reset' ? 'Verify & Reset' : 'Forgot Password?'; ?></div>
    <div class="brand-sub"><?php echo $step === 'reset' ? 'Aapke email pe bheja gaya code aur naya password daalein' : 'Apna email daalein, hum ek verification code bhejenge'; ?></div>

    <?php if ($step === 'email'): ?>
        <form action="" method="POST">
            <div class="fg">
                <label>Email Address</label>
                <div class="input-wrap">
                    <i class="fas fa-envelope"></i>
                    <input type="email" name="email" placeholder="you@email.com" required>
                </div>
            </div>
            <button type="submit" name="request_otp" class="btn-main">Send Verification Code</button>
        </form>
    <?php else: ?>
        <?php if ($resendMessage): ?><div class="info-msg"><?php echo htmlspecialchars($resendMessage); ?></div><?php endif; ?>
        <form action="" method="POST">
            <div class="fg">
                <label>Verification Code</label>
                <div class="input-wrap">
                    <i class="fas fa-shield-halved"></i>
                    <input type="text" name="otp" class="otp-input" placeholder="------" maxlength="6" required>
                </div>
            </div>
            <div class="fg">
                <label>New Password</label>
                <div class="input-wrap">
                    <i class="fas fa-lock"></i>
                    <input type="password" name="new_password" placeholder="New Password" minlength="6" required>
                </div>
            </div>
            <button type="submit" name="reset_password" class="btn-main">Reset Password</button>
        </form>
        <form action="" method="POST">
            <button type="submit" name="resend_otp" class="btn-secondary">Resend Code</button>
        </form>
    <?php endif; ?>

    <div class="login-link">
        <a href="auth/index"><i class="fas fa-arrow-left" style="margin-right:6px;font-size:11px"></i>Back to login</a>
    </div>
</div>
</body>
</html>
