<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

redirectIfLoggedIn();

$error = '';
$success = '';
$reset_link = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security check failed (CSRF). Please try again.";
    } else {
        $email = trim($_POST['email'] ?? '');
        
        if (empty($email)) {
            $error = "Please enter your email address.";
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format.";
        } else {
            try {
                // Check if user exists
                $stmt = $pdo->prepare("SELECT id, username FROM users WHERE email = ?");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user) {
                    // Generate reset token and expiration (1 hour)
                    $token = bin2hex(random_bytes(32));
                    $stmt_update = $pdo->prepare("
                        UPDATE users 
                        SET reset_token = ?, reset_token_expires = CURRENT_TIMESTAMP + INTERVAL '1 hour' 
                        WHERE id = ?
                    ");
                    $stmt_update->execute([$token, $user['id']]);
                    
                    // Build reset link
                    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
                    // Clean base path to handle directories correctly
                    $base_dir = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                    $reset_link = $protocol . "://" . $_SERVER['HTTP_HOST'] . $base_dir . "/reset_password?token=" . $token;
                    
                    // Dispatch notification
                    require_once __DIR__ . '/../includes/notification_helper.php';
                    sendMultichannelNotification($user['id'], 'password_reset', [
                        'username' => $user['username'],
                        'reset_link' => $reset_link
                    ]);
                    
                    $success = "A password reset link has been generated and dispatched.";
                } else {
                    $success = "If that email exists in our system, we have sent a reset link to it.";
                }
            } catch (PDOException $e) {
                $error = "An error occurred: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RENENET EDUCARE</title>
    <!-- Bootstrap 5 CSS -->
    <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.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        html { font-size: 16px; }
        @media (max-width: 576px) { html { font-size: 14px; } }
        body { font-size: calc(14px + 0.2vw); background-color: #f8f9fa; }
        .reset-card { border: none; border-radius: 12px; }
    </style>
</head>
<body class="d-flex align-items-center min-vh-100 py-4">
    <div class="container-fluid px-md-5">
        <div class="row justify-content-center">
            <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-5">
                <div class="card shadow-lg reset-card p-4">
                    <div class="card-body">
                        <div class="text-center mb-4">
                            <i class="bi bi-shield-lock-fill text-primary mb-2" style="font-size: 3.5rem;"></i>
                            <h2 class="fw-bold mt-2">Forgot Password</h2>
                            <p class="text-muted">Enter your email and we'll send you a password reset link.</p>
                        </div>

                        <?php if (!empty($error)): ?>
                            <div class="alert alert-danger shadow-sm border-0 mb-3" role="alert">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                <?php echo htmlspecialchars($error); ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($success)): ?>
                            <div class="alert alert-success shadow-sm border-0 mb-3" role="alert">
                                <i class="bi bi-check-circle-fill me-2"></i>
                                <?php echo htmlspecialchars($success); ?>
                            </div>
                            <?php if (!empty($reset_link)): ?>
                                <div class="alert alert-info border-0 shadow-sm mt-3" role="alert">
                                    <h6 class="fw-bold alert-heading"><i class="bi bi-info-circle-fill me-2"></i>Local Testing Reset Link</h6>
                                    <p class="small mb-2 text-break">Since SMTP mail setup might be inactive locally, click the link below to reset the password:</p>
                                    <a href="<?php echo htmlspecialchars($reset_link); ?>" class="btn btn-sm btn-outline-primary fw-bold w-100">Reset Password Now</a>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>

                        <form method="POST" action="forgot_password" class="needs-validation" novalidate>
                            <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                            
                            <div class="mb-4">
                                <label for="email" class="form-label">Email Address</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-envelope-fill"></i></span>
                                    <input type="email" class="form-control border-start-0 ps-0" id="email" name="email" required placeholder="e.g. user@example.com">
                                </div>
                            </div>

                            <div class="d-grid gap-2 mb-3">
                                <button type="submit" class="btn btn-primary btn-lg py-2">
                                    <i class="bi bi-send me-2"></i>Send Reset Link
                                </button>
                            </div>
                            <div class="text-center mt-3">
                                <a href="login" class="text-decoration-none small fw-bold"><i class="bi bi-arrow-left me-1"></i>Back to Login</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
