<?php
session_start();
include '../includes/db.php';
include '../includes/mail_config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;
require '../includes/PHPMailer/Exception.php';
require '../includes/PHPMailer/PHPMailer.php';
require '../includes/PHPMailer/SMTP.php';

$message    = "";
$msg_type   = "";
$reset_link = "";

if (empty($_SESSION['csrf_forgot'])) $_SESSION['csrf_forgot'] = bin2hex(random_bytes(32));

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!isset($_POST['csrf_forgot']) || !hash_equals($_SESSION['csrf_forgot'], $_POST['csrf_forgot'])) {
        $message  = "Invalid request. Please try again.";
        $msg_type = "danger";
    } else {
        $identifier = trim($_POST['identifier'] ?? '');

        if (empty($identifier)) {
            $message  = "User ID ya Email daalna zaroori hai.";
            $msg_type = "danger";
        } else {
            $stmt = $conn->prepare("SELECT id, email, username FROM admin_users WHERE username=? OR email=? LIMIT 1");
            $stmt->bind_param("ss", $identifier, $identifier);
            $stmt->execute(); $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $stmt->bind_result($admin_id, $admin_email, $admin_username);
                $stmt->fetch(); $stmt->close();

                // Wrong email entered?
                if (filter_var($identifier, FILTER_VALIDATE_EMAIL) && strtolower($identifier) !== strtolower($admin_email ?? '')) {
                    $message  = "❌ Wrong Email ID. Sirf registered email se reset link milegi.";
                    $msg_type = "danger";
                } elseif (filter_var($identifier, FILTER_VALIDATE_EMAIL) && empty($admin_email)) {
                    $message  = "❌ Is account mein email registered nahi hai. Pehle email add karein.";
                    $msg_type = "warning";
                } else {
                    // Generate token
                    $raw_token    = bin2hex(random_bytes(32));
                    $hashed_token = hash('sha256', $raw_token);
                    $expiry       = date('Y-m-d H:i:s', strtotime('+1 hour'));

                    $upd = $conn->prepare("UPDATE admin_users SET reset_token=?, reset_token_expiry=? WHERE id=?");
                    $upd->bind_param("ssi", $hashed_token, $expiry, $admin_id);
                    $upd->execute(); $upd->close();

                    $protocol  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
                    $reset_url = $protocol . "://" . $_SERVER['HTTP_HOST'] . "/bm/admin/reset_password.php?token=" . urlencode($raw_token) . "&id=" . $admin_id;

                    $mail_sent = false; $mail_error = "";
                    if (!empty($admin_email)) {
                        $mail = new PHPMailer(true);
                        try {
                            $mail->isSMTP(); $mail->Host = MAIL_HOST; $mail->SMTPAuth = true;
                            $mail->Username = MAIL_USERNAME; $mail->Password = MAIL_PASSWORD;
                            $mail->SMTPSecure = MAIL_ENCRYPTION; $mail->Port = MAIL_PORT; $mail->CharSet = 'UTF-8';
                            $mail->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
                            $mail->addAddress($admin_email);
                            $mail->isHTML(true);
                            $mail->Subject = 'Balimeen Admin – Password Reset';
                            $mail->Body = '<!DOCTYPE html><html><body style="font-family:Arial,sans-serif;background:#f4f7f6;padding:30px;">
<div style="max-width:500px;margin:auto;background:#fff;border-radius:16px;padding:30px;box-shadow:0 4px 12px rgba(0,0,0,0.1);">
  <h2 style="color:#00bfff;text-align:center;">&#128274; Password Reset</h2>
  <p>Hello Admin,</p>
  <p>Aapne password reset request ki hai. Neeche button click karein (1 ghante valid):</p>
  <div style="text-align:center;margin:25px 0;">
    <a href="' . htmlspecialchars($reset_url) . '" style="background:#00bfff;color:#fff;padding:14px 30px;border-radius:25px;text-decoration:none;font-weight:bold;">Reset Password</a>
  </div>
  <p style="font-size:12px;word-break:break-all;background:#f0f0f0;padding:10px;border-radius:8px;">' . htmlspecialchars($reset_url) . '</p>
  <p style="color:#999;font-size:12px;text-align:center;">Balimeen Pvt Ltd &bull; balimeenpvtltd@gmail.com</p>
</div></body></html>';
                            $mail->AltBody = "Reset link:\n" . $reset_url;
                            $mail->send(); $mail_sent = true;
                        } catch (MailException $e) { $mail_error = $mail->ErrorInfo; }
                    }

                    if ($mail_sent) {
                        $message  = "✅ Reset link <strong>" . htmlspecialchars($admin_email) . "</strong> par bhej di gayi! Inbox aur Spam check karein.";
                        $msg_type = "success";
                    } else {
                        $reset_link = $reset_url;
                        $message    = "Email send nahi ho saki" . ($mail_error ? " (" . htmlspecialchars($mail_error) . ")" : "") . ". Neeche link use karein:";
                        $msg_type   = "warning";
                    }
                }
            } else {
                $stmt->close();
                if (filter_var($identifier, FILTER_VALIDATE_EMAIL)) {
                    $message  = " ❌ Wrong Email ID. This email is not registered.";
                    $msg_type = "danger";
                } else {
                    $message  = "❌ Invalid User ID.";
                    $msg_type = "danger";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password – Balimeen Admin</title>
    <link rel="shortcut icon" href="/bm/BM LOGO.jpg" type="image/jpeg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f4f7f6; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; }
        .reset-card { width: 100%; max-width: 420px; padding: 2rem; border-radius: 30px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); background: deepskyblue; }
        .form-label { color: #fff; font-size: 13px; font-weight: 600; }
        .reset-link-box { background: rgba(255,255,255,0.9); border-radius: 8px; padding: 10px 12px; font-size: 12px; word-break: break-all; margin-top: 8px; }
        .back-link { font-size: 13px; color: #fff; text-decoration: underline; }
        .email-info { font-size: 12px; color: #fff; text-align: center; margin-top: 10px; }
        .registered-badge { background: rgba(255,255,255,0.9); border-radius: 10px; padding: 6px 12px; font-size: 12px; color: #005a8e; font-weight: 600; margin-bottom: 14px; text-align: center; }
        h3 { color: #fff; }
    </style>
</head>
<body>
<div class="reset-card">
    <h3 class="text-center mb-1"><i class="fa fa-key me-2"></i>Forgot Password</h3>
    <p class="text-center text-white mb-3" style="font-size:12px;">User ID ya registered Email ID enter karein — reset link milegi.</p>

    <!-- Registered email badge -->
    <div class="registered-badge">
        <i class="fa fa-check-circle text-success me-1"></i>Registered Email: <strong>balimeenpvtltd@gmail.com</strong>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $msg_type; ?>">
            <?php echo $message; ?>
            <?php if ($reset_link): ?>
                <div class="reset-link-box">
                    <a href="<?php echo htmlspecialchars($reset_link); ?>"><?php echo htmlspecialchars($reset_link); ?></a>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php if ($msg_type !== 'success'): ?>
    <form method="POST" autocomplete="off">
        <input type="hidden" name="csrf_forgot" value="<?php echo htmlspecialchars($_SESSION['csrf_forgot']); ?>">
        <div class="mb-3">
            <label class="form-label">User ID ya Email Address</label>
            <input type="text" class="form-control" name="identifier"
                   placeholder="User ID ya balimeenpvtltd@gmail.com"
                   value="<?php echo (isset($_POST['identifier']) && $msg_type === 'danger') ? htmlspecialchars($_POST['identifier']) : ''; ?>"
                   required autocomplete="off">
        </div>
        <button type="submit" class="btn btn-primary w-100">
            <i class="fa fa-paper-plane me-1"></i>Send Reset Link
        </button>
    </form>
    <?php endif; ?>

    <hr style="border-color:rgba(255,255,255,0.3);margin:1rem 0;">
    <div class="text-center">
        <a href="login.php" class="back-link"><i class="fa fa-arrow-left me-1"></i>Back to Login</a>
    </div>
    <div class="email-info"><i class="fa fa-envelope me-1"></i>balimeenpvtltd@gmail.com</div>
</div>
</body>
</html>
