<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Forgot Password Page
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/constants.php';
require_once dirname(__DIR__) . '/config/database.php';
require_once dirname(__DIR__) . '/config/helpers.php';
require_once dirname(__DIR__) . '/config/auth.php';
require_once dirname(__DIR__) . '/config/csrf.php';
require_once dirname(__DIR__) . '/config/mailer.php';

// Redirect if already logged in
if (is_logged_in()) {
    redirect('dashboard.php');
}

// Handle form submission
$message = '';
$error = '';
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $email = sanitize_input($_POST['email'] ?? '');
        
        if (empty($email)) {
            $error = 'Please enter your email address';
        } elseif (!validate_email($email)) {
            $error = 'Please enter a valid email address';
        } else {
            // Check if email exists
            $user = db_fetch_one(
                "SELECT user_id, first_name, email FROM users WHERE email = ? AND is_active = 1",
                [$email]
            );
            
            if ($user) {
                // Generate reset token
                $token = generate_password_reset_token($email);
                
                if ($token) {
                    // Send reset email
                    $sent = send_password_reset_email($email, $token);
                    
                    if ($sent) {
                        $message = 'Password reset instructions have been sent to your email address.';
                        
                        // Log the action
                        audit_log($user['user_id'], 'password_reset_request', 'users', $user['user_id']);
                        
                        // Clear email field for security
                        $email = '';
                    } else {
                        $error = 'Failed to send reset email. Please try again later.';
                        log_message("Failed to send password reset email to: $email", 'ERROR');
                    }
                } else {
                    $error = 'Failed to generate reset token. Please try again.';
                }
            } else {
                // Don't reveal that email doesn't exist (security best practice)
                $message = 'If your email is registered, you will receive password reset instructions.';
                
                // Still log for monitoring
                log_message("Password reset attempted for non-existent email: $email", 'INFO');
            }
        }
    }
}

// Set page title
$page_title = 'Forgot Password';
?>

<!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 APP_NAME; ?></title>
    
    <!-- CSRF Meta Tags -->
    <?php echo csrf_meta_tags(); ?>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <link rel="stylesheet" href="<?php echo assets_url('css/style.css'); ?>?v=<?php echo APP_VERSION; ?>">
    
    <style>
        :root {
            --primary-color: #007bff;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .forgot-container {
            width: 100%;
            max-width: 450px;
            animation: fadeIn 0.5s ease;
        }
        
        .forgot-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .forgot-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
        }
        
        .forgot-header {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .forgot-header h1 {
            margin: 0;
            font-size: 2rem;
            font-weight: 600;
        }
        
        .forgot-header p {
            margin: 0.5rem 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }
        
        .forgot-body {
            padding: 2rem;
        }
        
        .resort-logo {
            width: 100px;
            height: 100px;
            background: white;
            border-radius: 50%;
            margin: -70px auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .resort-logo img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
        }
        
        .info-text {
            text-align: center;
            color: #6c757d;
            margin-bottom: 2rem;
            font-size: 0.95rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .form-group i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
            font-size: 1.1rem;
            z-index: 10;
        }
        
        .form-control {
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            border: 2px solid #e0e0e0;
            border-radius: 50px;
            font-size: 1rem;
            transition: all 0.3s ease;
            height: auto;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
            outline: none;
        }
        
        .form-control.is-invalid {
            border-color: var(--danger-color);
        }
        
        .invalid-feedback {
            display: block;
            margin-top: 0.5rem;
            padding-left: 1rem;
            color: var(--danger-color);
            font-size: 0.875rem;
        }
        
        .btn-reset {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            border: none;
            border-radius: 50px;
            padding: 0.75rem;
            font-size: 1.1rem;
            font-weight: 600;
            color: white;
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            margin-bottom: 1rem;
        }
        
        .btn-reset:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.4);
        }
        
        .btn-reset:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .btn-reset .spinner-border {
            width: 1.2rem;
            height: 1.2rem;
            margin-right: 0.5rem;
        }
        
        .btn-back {
            background: transparent;
            border: 2px solid var(--primary-color);
            border-radius: 50px;
            padding: 0.75rem;
            font-size: 1rem;
            font-weight: 600;
            color: var(--primary-color);
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-back:hover {
            background: var(--primary-color);
            color: white;
            text-decoration: none;
        }
        
        .alert {
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            margin-bottom: 1.5rem;
            border: none;
            animation: slideIn 0.3s ease;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .login-footer {
            margin-top: 2rem;
            text-align: center;
            color: white;
            font-size: 0.9rem;
        }
        
        .login-footer a {
            color: white;
            text-decoration: none;
            font-weight: 600;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .developer-credit {
            margin-top: 2rem;
            font-size: 0.85rem;
            color: rgba(255,255,255,0.7);
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .forgot-header {
                padding: 1.5rem;
            }
            
            .forgot-header h1 {
                font-size: 1.5rem;
            }
            
            .forgot-body {
                padding: 1.5rem;
            }
            
            .resort-logo {
                width: 80px;
                height: 80px;
                margin-top: -60px;
            }
            
            .resort-logo img {
                width: 60px;
                height: 60px;
            }
            
            .form-control {
                padding: 0.6rem 1rem 0.6rem 2.2rem;
                font-size: 0.95rem;
            }
            
            .btn-reset, .btn-back {
                padding: 0.6rem;
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="forgot-container">
        <div class="forgot-card">
            <div class="forgot-header">
                <h1>Forgot Password</h1>
                <p>Reset your password</p>
            </div>
            
            <div class="forgot-body">
                <!-- Resort Logo -->
                <div class="resort-logo">
                    <img src="<?php echo assets_url('img/logo.png'); ?>" alt="Ruhondo Beach Resort">
                </div>
                
                <!-- Info Text -->
                <div class="info-text">
                    <i class="fas fa-info-circle mr-1"></i>
                    Enter your email address and we'll send you instructions to reset your password.
                </div>
                
                <!-- Messages -->
                <?php if ($message): ?>
                    <div class="alert alert-success" role="alert">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo escape_html($message); ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <?php echo escape_html($error); ?>
                    </div>
                <?php endif; ?>
                
                <!-- Reset Form -->
                <form method="POST" action="<?php echo base_url('forgot-password.php'); ?>" id="resetForm">
                    <?php echo csrf_field(); ?>
                    
                    <div class="form-group">
                        <i class="fas fa-envelope"></i>
                        <input type="email" 
                               class="form-control <?php echo $error ? 'is-invalid' : ''; ?>" 
                               id="email" 
                               name="email" 
                               placeholder="Your Email Address"
                               value="<?php echo escape_html($email); ?>" 
                               required 
                               autofocus>
                    </div>
                    
                    <button type="submit" class="btn-reset" id="resetBtn">
                        <span class="normal-state">
                            <i class="fas fa-paper-plane mr-2"></i> Send Reset Instructions
                        </span>
                        <span class="loading-state d-none">
                            <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                            Sending...
                        </span>
                    </button>
                    
                    <a href="<?php echo base_url('login.php'); ?>" class="btn-back">
                        <i class="fas fa-arrow-left mr-2"></i> Back to Login
                    </a>
                </form>
                
                <!-- Security Note -->
                <div class="mt-4 pt-3 border-top text-center">
                    <small class="text-muted">
                        <i class="fas fa-shield-alt mr-1"></i>
                        For security reasons, reset links expire after <?php echo PASSWORD_RESET_EXPIRY / 3600; ?> hour.
                    </small>
                </div>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="login-footer">
            <p>&copy; <?php echo date('Y'); ?> <?php echo APP_NAME; ?>. All rights reserved.</p>
            <div class="developer-credit">
                Developed by <a href="#" target="_blank"><?php echo APP_COMPANY; ?></a>
            </div>
        </div>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            const $form = $('#resetForm');
            const $resetBtn = $('#resetBtn');
            const $normalState = $resetBtn.find('.normal-state');
            const $loadingState = $resetBtn.find('.loading-state');
            let submitted = false;
            
            // Form submission
            $form.on('submit', function() {
                if (submitted) {
                    return false;
                }
                
                // Show loading state
                $resetBtn.prop('disabled', true);
                $normalState.addClass('d-none');
                $loadingState.removeClass('d-none');
                
                submitted = true;
                return true;
            });
            
            // Remove is-invalid class on input
            $('#email').on('input', function() {
                $(this).removeClass('is-invalid');
            });
            
            // Auto-fill from URL parameters (for testing)
            const urlParams = new URLSearchParams(window.location.search);
            const email = urlParams.get('email');
            if (email) {
                $('#email').val(email);
            }
            
            // Validate email on blur
            $('#email').on('blur', function() {
                const email = $(this).val();
                if (email && !isValidEmail(email)) {
                    $(this).addClass('is-invalid');
                    if ($(this).next('.invalid-feedback').length === 0) {
                        $(this).after('<div class="invalid-feedback">Please enter a valid email address</div>');
                    }
                }
            });
            
            function isValidEmail(email) {
                const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                return re.test(email);
            }
            
            // Prevent double submission on page refresh
            if (window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }
        });
    </script>
</body>
</html>