<?php
require_once 'includes/db_connect.php';
$message = '';
$mobile = $_GET['mobile'] ?? '';
$step = $_GET['step'] ?? 'verify_otp';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Step 1: Handle OTP verification
    if (isset($_POST['verify_otp'])) {
        $otp_submitted = $_POST['otp'];
        $stmt = $conn->prepare("SELECT otp_code, created_at FROM password_resets WHERE mobile = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->bind_param("s", $mobile);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows == 1) {
            $row = $result->fetch_assoc();
            $time_diff = time() - strtotime($row['created_at']);
            if ($time_diff > 300) { // OTP is valid for 5 minutes (300 seconds)
                $message = '<div class="alert alert-danger">OTP-এর মেয়াদ শেষ। আবার চেষ্টা করুন।</div>';
            } elseif (password_verify($otp_submitted, $row['otp_code'])) {
                $_SESSION['reset_authorized'] = true;
                $_SESSION['reset_mobile'] = $mobile;
                header("Location: reset_password.php?step=new_password");
                exit;
            } else {
                $message = '<div class="alert alert-danger">আপনি ভুল OTP দিয়েছেন।</div>';
            }
        }
    }
    // Step 2: Handle new password submission
    elseif (isset($_POST['set_password'])) {
        if (!isset($_SESSION['reset_authorized']) || $_SESSION['reset_mobile'] != $mobile) {
            die("Unauthorized access.");
        }
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        if ($new_password !== $confirm_password || strlen($new_password) < 6) {
            $message = '<div class="alert alert-danger">পাসওয়ার্ড দুটি মেলেনি অথবা ৬ অক্ষরের কম।</div>';
            $step = 'new_password'; // Stay on the new password step
        } else {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE mobile = ?");
            $stmt->bind_param("ss", $hashed_password, $mobile);
            $stmt->execute();
            // Clean up session and password_resets table
            $conn->query("DELETE FROM password_resets WHERE mobile = '$mobile'");
            unset($_SESSION['reset_authorized'], $_SESSION['reset_mobile'], $_SESSION['debug_otp']);
            $step = 'success';
        }
    }
}
?>
<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>নতুন পাসওয়ার্ড সেট</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body style="background-color:#f0f2f5;"><div class="container" style="max-width:400px; margin-top:100px;"><div class="card p-4">
    <?php if ($step === 'verify_otp'): ?>
        <h3 class="text-center">OTP ভেরিফিকেশন</h3><p class="text-center text-muted">আপনার মোবাইলে পাঠানো ৬-সংখ্যার কোডটি দিন।</p><?php echo $message; ?>
        <?php if(isset($_SESSION['debug_otp'])): ?><div class="alert alert-info"><b>For Testing:</b> Your OTP is <?php echo $_SESSION['debug_otp']; ?></div><?php endif; ?>
        <form method="POST" class="mt-3">
            <div class="mb-3"><label class="form-label">OTP কোড</label><input type="number" name="otp" class="form-control" required></div>
            <button type="submit" name="verify_otp" class="btn btn-primary w-100">যাচাই করুন</button>
        </form>
    <?php elseif ($step === 'new_password'): ?>
        <h3 class="text-center">নতুন পাসওয়ার্ড দিন</h3><?php echo $message; ?>
        <form method="POST" class="mt-3">
            <div class="mb-3"><label class="form-label">নতুন পাসওয়ার্ড</label><input type="password" name="new_password" class="form-control" required></div>
            <div class="mb-3"><label class="form-label">পাসওয়ার্ড নিশ্চিত করুন</label><input type="password" name="confirm_password" class="form-control" required></div>
            <button type="submit" name="set_password" class="btn btn-primary w-100">পাসওয়ার্ড পরিবর্তন করুন</button>
        </form>
    <?php elseif ($step === 'success'): ?>
        <div class="text-center"><h3 class="text-success">সফল!</h3><p>আপনার পাসওয়ার্ড সফলভাবে পরিবর্তন করা হয়েছে।</p><a href="login.php" class="btn btn-primary">এখন লগইন করুন</a></div>
    <?php endif; ?>
</div></div></body></html>