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

$message = "";
$message_type = "";

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// ── Admin password change (sirf logged-in admin ke liye) ──
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $message = "Invalid request. Please try again.";
        $message_type = "danger";
    } else {
        $new_pwd     = $_POST['new_password']     ?? '';
        $confirm_pwd = $_POST['confirm_password'] ?? '';

        if (strlen($new_pwd) < 6) {
            $message = "Password kam se kam 6 characters ka hona chahiye.";
            $message_type = "danger";
        } elseif ($new_pwd !== $confirm_pwd) {
            $message = "Dono passwords match nahi karte.";
            $message_type = "danger";
        } else {
            $hashed = password_hash($new_pwd, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE admin_users SET password = ?, reset_token = NULL, reset_token_expiry = NULL WHERE username = 'admin'");
            $stmt->bind_param("s", $hashed);
            if ($stmt->execute()) {
                $message = "✅ Password successfully change ho gaya! Ab naye password se login karein.";
                $message_type = "success";
            } else {
                $message = "❌ Error. Please try again.";
                $message_type = "danger";
            }
            $stmt->close();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change 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; }
        .card-box { width: 100%; max-width: 420px; padding: 2rem; border-radius: 30px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); background: deepskyblue; }
        .password-wrapper { position: relative; }
        .password-wrapper .toggle-eye { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #555; background: none; border: none; padding: 0; }
        .password-wrapper input { padding-right: 40px; }
        .back-link { font-size: 13px; color: #fff; text-decoration: underline; }
        .email-info { font-size: 12px; color: #fff; text-align: center; margin-top: 10px; }
    </style>
    <?php if ($message_type === 'success'): ?>
    <meta http-equiv="refresh" content="3;url=login.php">
    <?php endif; ?>
</head>
<body>
    <div class="card-box">
        <h3 class="text-center text-white mb-2"><i class="fa fa-lock me-2"></i>Change Password</h3>
        <p class="text-center text-white mb-3" style="font-size:13px;">Apna naya custom password set karein</p>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?>">
                <?php echo htmlspecialchars($message); ?>
                <?php if ($message_type === 'success'): ?>
                    <br><small>3 seconds mein login page par redirect ho jayenge...</small>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($message_type !== 'success'): ?>
        <form method="POST" action="" autocomplete="off">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">

            <div class="mb-3">
                <label for="new_password" class="form-label text-white">Naya Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="new_password" name="new_password"
                           placeholder="Minimum 6 characters" required autocomplete="new-password">
                    <button type="button" class="toggle-eye" onclick="togglePwd('new_password','eye1')">
                        <i class="fa fa-eye" id="eye1"></i>
                    </button>
                </div>
            </div>

            <div class="mb-3">
                <label for="confirm_password" class="form-label text-white">Confirm Password</label>
                <div class="password-wrapper">
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password"
                           placeholder="Password dobara dalein" required autocomplete="new-password">
                    <button type="button" class="toggle-eye" onclick="togglePwd('confirm_password','eye2')">
                        <i class="fa fa-eye" id="eye2"></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="btn btn-primary w-100">
                <i class="fa fa-save me-1"></i>Save New Password
            </button>
        </form>
        <?php endif; ?>

        <div class="mt-3 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>
    <script>
        function togglePwd(fieldId, iconId) {
            var f = document.getElementById(fieldId);
            var i = document.getElementById(iconId);
            f.type = f.type === 'password' ? 'text' : 'password';
            i.classList.toggle('fa-eye');
            i.classList.toggle('fa-eye-slash');
        }
    </script>
</body>
</html>
