<?php
session_start();

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';

if (!isInstalled()) {
    redirect('/install/');
}

$csrf = new CSRF();
$message = '';
$success = false;
$step = 'email';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST[CSRF_TOKEN_NAME] ?? '';

    if (!$csrf->verify($token)) {
        $message = 'Invalid security token. Please try again.';
    } else {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'request_reset':
                    $email = trim($_POST['email'] ?? '');
                    if (empty($email)) {
                        $message = 'Please enter your email address.';
                    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $message = 'Please enter a valid email address.';
                    } else {
                        $db = Database::getInstance();
                        $stmt = $db->query("SELECT id, email FROM users WHERE email = ? AND status = 1", [$email]);
                        $user = $stmt->fetch();

                        if ($user) {
                            $resetToken = bin2hex(random_bytes(32));
                            $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));

                            $db->delete('password_resets', 'email = ?', [$email]);

                            $db->insert('password_resets', [
                                'email'      => $email,
                                'token'      => hash('sha256', $resetToken),
                                'created_at' => date('Y-m-d H:i:s'),
                                'expires_at' => $expiry,
                            ]);

                            $resetUrl = APP_URL . '/forgot-password.php?token=' . $resetToken;

                            error_log("Password reset requested for email: {$email}");
                        }

                        $success = true;
                        $message = 'If the email address exists in our system, you will receive a password reset link shortly.';
                    }
                    break;

                case 'reset_password':
                    $resetToken = $_POST['reset_token'] ?? '';
                    $newPassword = $_POST['new_password'] ?? '';
                    $confirmPassword = $_POST['confirm_password'] ?? '';

                    if (empty($resetToken)) {
                        $message = 'Invalid reset token.';
                    } elseif (strlen($newPassword) < 6) {
                        $message = 'Password must be at least 6 characters long.';
                    } elseif ($newPassword !== $confirmPassword) {
                        $message = 'Passwords do not match.';
                    } else {
                        $db = Database::getInstance();
                        $hashedToken = hash('sha256', $resetToken);

                        $stmt = $db->query(
                            "SELECT id, email, expires_at FROM password_resets WHERE token = ? AND expires_at > NOW()",
                            [$hashedToken]
                        );
                        $resetRecord = $stmt->fetch();

                        if ($resetRecord) {
                            $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                            $db->update('users', ['password' => $hashedPassword], 'email = ?', [$resetRecord['email']]);
                            $db->delete('password_resets', 'id = ?', [$resetRecord['id']]);

                            $success = true;
                            $message = 'Your password has been reset successfully. You can now login with your new password.';
                            $step = 'success';
                        } else {
                            $message = 'Invalid or expired reset token. Please request a new one.';
                        }
                    }
                    break;
            }
        }
    }
}

$resetToken = $_GET['token'] ?? $_POST['reset_token'] ?? '';
if (!empty($resetToken) && $step !== 'success') {
    $step = 'reset';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - <?php echo sanitize(APP_NAME); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .container {
            width: 100%;
            max-width: 440px;
            padding: 15px;
        }
        .card {
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
            padding: 40px;
            animation: slideUp 0.5s ease-out;
        }
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo h2 {
            font-size: 24px;
            font-weight: 700;
            color: #333;
            margin-bottom: 8px;
        }
        .logo p { color: #888; font-size: 14px; }
        .logo .icon-circle {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
        }
        .logo .icon-circle i { font-size: 26px; color: #fff; }
        .form-floating { margin-bottom: 16px; }
        .form-floating .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 16px 14px;
            height: 52px;
            transition: border-color 0.3s;
        }
        .form-floating .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.15);
        }
        .form-floating label { padding: 16px 14px; }
        .btn-primary-custom {
            width: 100%;
            height: 50px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: #fff;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
            color: #fff;
        }
        .back-link {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
        }
        .back-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }
        .back-link a:hover { text-decoration: underline; }
        .alert { border-radius: 10px; font-size: 14px; }
        .success-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: #d4edda;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }
        .success-icon i { font-size: 40px; color: #28a745; }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="logo">
                <div class="icon-circle">
                    <i class="bi bi-key"></i>
                </div>
                <h2>Forgot Password?</h2>
                <p>Enter your email to reset your password</p>
            </div>

            <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $success ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                    <i class="bi bi-<?php echo $success ? 'check-circle-fill' : 'exclamation-triangle-fill'; ?> me-2"></i>
                    <?php echo sanitize($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($step === 'success'): ?>
                <div class="text-center">
                    <div class="success-icon">
                        <i class="bi bi-check-lg"></i>
                    </div>
                    <p class="text-muted mb-4">Your password has been reset successfully.</p>
                    <a href="login.php" class="btn btn-primary-custom">
                        <i class="bi bi-box-arrow-in-right me-2"></i>Go to Login
                    </a>
                </div>

            <?php elseif ($step === 'reset'): ?>
                <form method="POST" action="">
                    <?php echo $csrf->field(); ?>
                    <input type="hidden" name="action" value="reset_password">
                    <input type="hidden" name="reset_token" value="<?php echo sanitize($resetToken); ?>">

                    <div class="form-floating">
                        <input type="password" class="form-control" id="new_password" name="new_password"
                               placeholder="New Password" required minlength="6">
                        <label for="new_password"><i class="bi bi-lock me-2"></i>New Password</label>
                    </div>

                    <div class="form-floating">
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password"
                               placeholder="Confirm Password" required minlength="6">
                        <label for="confirm_password"><i class="bi bi-lock-fill me-2"></i>Confirm Password</label>
                    </div>

                    <button type="submit" class="btn btn-primary-custom mt-2">
                        <i class="bi bi-check-lg me-2"></i>Reset Password
                    </button>
                </form>

            <?php else: ?>
                <form method="POST" action="">
                    <?php echo $csrf->field(); ?>
                    <input type="hidden" name="action" value="request_reset">

                    <div class="form-floating">
                        <input type="email" class="form-control" id="email" name="email"
                               placeholder="Email address" required autofocus
                               value="<?php echo sanitize($_POST['email'] ?? ''); ?>">
                        <label for="email"><i class="bi bi-envelope me-2"></i>Email address</label>
                    </div>

                    <button type="submit" class="btn btn-primary-custom mt-2">
                        <i class="bi bi-send me-2"></i>Send Reset Link
                    </button>
                </form>
            <?php endif; ?>

            <div class="back-link">
                <a href="login.php"><i class="bi bi-arrow-left me-1"></i>Back to Login</a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
