<?php
/**
 * FORGOT PASSWORD PAGE
 * File: auth/forgot-password.php
 * Handles password reset requests
 */

require_once '../app/Core/init.php';

// Redirect if already logged in
if (Auth::check()) {
    $user_type = $_SESSION['user_type'];
    if ($user_type === 'admin') {
        redirect('../admin/index.php');
    } elseif ($user_type === 'vendor') {
        redirect('../vendor/index.php');
    } elseif ($user_type === 'customer') {
        redirect('../index.php');
    }
}

$errors = [];
$email = '';
$success = false;

// Handle forgot password form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!Security::validateToken($token)) {
        $errors['general'] = 'Invalid security token. Please refresh and try again.';
    } else {
        $email = trim($_POST['email'] ?? '');
        
        // Validate email
        if (empty($email)) {
            $errors['email'] = 'Email is required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Please enter a valid email address';
        }
        
        // If no errors, process password reset
        if (empty($errors)) {
            try {
                $userModel = new User();
                $user = $userModel->findByEmail($email);
                
                if ($user) {
                    // Generate password reset token
                    $reset_token = bin2hex(random_bytes(32));
                    $token_expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
                    
                    // Save reset token to database
                    $userModel->setResetToken($user['id'], $reset_token, $token_expiry);
                    
                    // Get user name
                    $name = '';
                    if ($user['user_type'] === 'customer') {
                        $customerModel = new Customer();
                        $customer = $customerModel->findByUserId($user['id']);
                        $name = $customer['first_name'] ?? 'there';
                    } elseif ($user['user_type'] === 'vendor') {
                        $vendorModel = new Vendor();
                        $vendor = $vendorModel->findByUserId($user['id']);
                        $name = $vendor['business_name'] ?? 'there';
                    }
                    
                    // Send password reset email
                    $mailer = new Mailer();
                    $mailer->sendPasswordResetEmail($email, $name, $reset_token);
                    
                    $success = true;
                } else {
                    // Don't reveal if email exists or not for security
                    $success = true;
                }
            } catch (Exception $e) {
                log_message("Forgot password error: " . $e->getMessage(), 'error');
                $errors['general'] = 'An error occurred. Please try again.';
            }
        }
    }
}

$page_title = "Forgot Password - " . APP_NAME;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="../assets/images/favicon.png">
    <title><?= $page_title ?></title>
    <link href="../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../assets/plugins/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Header -->
    <?php include '../templates/layouts/frontend/header.php'; ?>
    
    <div class="container-fluid p-0">
        <div class="row g-0">
            <div class="col-xl-5">
                <div class="account-page-area p-4 p-md-5">
                    
                    <?php if ($success): ?>
                        <!-- Success Message -->
                        <div class="text-center">
                            <div class="mb-4">
                                <i class="fas fa-envelope-circle-check text-success" style="font-size: 64px;"></i>
                            </div>
                            <h2 class="fw-semibold mb-3">Check Your Email!</h2>
                            <p class="mb-4">We've sent password reset instructions to:</p>
                            <p class="fw-bold text-primary mb-4"><?= Security::escapeOutput($email) ?></p>
                            <p class="text-muted mb-4">Please check your email and click the reset link. The link will expire in 1 hour.</p>
                            <div class="alert alert-info text-start">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Didn't receive the email?</strong> Check your spam folder or try again.
                            </div>
                            <a href="login.php" class="btn btn-primary btn-lg">Back to Login</a>
                        </div>
                    <?php else: ?>
                        <!-- Header -->
                        <div class="mb-4">
                            <h2 class="fw-semibold mb-2">Forgot Password?</h2>
                            <p class="text-muted">No worries! Enter your email and we'll send you reset instructions.</p>
                        </div>
                        
                        <!-- Display errors -->
                        <?php if (isset($errors['general'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                <?= Security::escapeOutput($errors['general']) ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Forgot Password Form -->
                        <form method="POST" action="" class="register-form">
                            <?= Security::csrfField() ?>
                            
                            <!-- Email Field -->
                            <div class="mb-4">
                                <label class="form-label">Email Address <span class="text-danger">*</span></label>
                                <input type="email" name="email" class="form-control <?= isset($errors['email']) ? 'is-invalid' : '' ?>" 
                                       value="<?= Security::escapeOutput($email) ?>" placeholder="Enter your registered email" required>
                                <?php if (isset($errors['email'])): ?>
                                    <div class="invalid-feedback"><?= $errors['email'] ?></div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Submit Button -->
                            <button type="submit" class="btn btn-primary btn-lg w-100">
                                <i class="fas fa-paper-plane me-2"></i>Send Reset Link
                            </button>
                        </form>
                        
                        <!-- Bottom Text -->
                        <div class="bottom-text text-center mt-4">
                            Remember your password? <a href="login.php" class="fw-medium text-decoration-underline">Sign In</a>
                            <br>
                            Don't have an account? <a href="register.php" class="fw-medium text-decoration-underline">Sign Up</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-xl-7 d-none d-xl-block">
                <div class="background-image bg-light d-flex flex-column h-100 justify-content-center p-5 rounded-4" data-image-src="../assets/images/lines.svg">
                    <div class="py-5 text-center">
                        <div class="mb-5">
                            <h2 class="fw-semibold">Secure Account Recovery</h2>
                            <p>We'll help you get back to your account quickly and securely</p>
                        </div>
                        <img src="../assets/images/png-img/login.png" alt="" class="img-fluid">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <?php include '../templates/layouts/frontend/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="../assets/plugins/jQuery/jquery.min.js"></script>
    <script src="../assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/script.js"></script>
</body>
</html>
