<?php
require_once 'config/config.php';

$message = '';
$messageType = '';
$showForm = true;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize($_POST['email'] ?? '');
    
    if (!empty($email) && isValidEmail($email)) {
        // Check if user exists
        $stmt = $db->prepare("SELECT id, full_name, email FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Generate reset token (expires in 10 minutes)
            $resetToken = bin2hex(random_bytes(32));
            $expiresAt = date('Y-m-d H:i:s', strtotime('+10 minutes'));
            
            // Store reset token
            $stmt = $db->prepare("
                INSERT INTO password_resets (user_id, token, expires_at, created_at) 
                VALUES (?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE token = ?, expires_at = ?, created_at = NOW()
            ");
            $stmt->execute([$user['id'], $resetToken, $expiresAt, $resetToken, $expiresAt]);
            
            // Send reset email
            $result = sendPasswordResetEmail($user['email'], $user['full_name'], $resetToken);
            
            if ($result['success']) {
                $message = 'Password reset instructions have been sent to your email address.';
                $messageType = 'success';
                $showForm = false;
            } else {
                $message = 'Failed to send email. Please try again later.';
                $messageType = 'error';
            }
        } else {
            // Don't reveal if email exists or not for security
            $message = 'If an account with that email exists, you will receive password reset instructions.';
            $messageType = 'success';
            $showForm = false;
        }
    } else {
        $message = 'Please enter a valid email address.';
        $messageType = 'error';
    }
}

$pageTitle = 'Forgot Password';
include 'includes/header.php';
?>

<style>
    .auth-container { min-height: calc(100vh - 200px); display: flex; align-items: center; justify-content: center; padding: 40px 20px; background: linear-gradient(135deg, #f0f4ff 0%, #e8f5e9 100%); }
    .auth-card { background: white; border-radius: 24px; box-shadow: 0 20px 60px rgba(0,0,0,0.1); overflow: hidden; max-width: 450px; width: 100%; }
    .auth-header { background: linear-gradient(135deg, #211594, #1a0f7a); padding: 40px; text-align: center; }
    .auth-header h1 { color: white; font-size: 28px; margin-bottom: 8px; }
    .auth-header p { color: rgba(255,255,255,0.8); font-size: 14px; }
    .auth-body { padding: 40px; }
    .form-group { margin-bottom: 24px; }
    .form-group label { display: block; font-size: 14px; font-weight: 600; color: #374151; margin-bottom: 8px; }
    .form-group input { width: 100%; padding: 14px 18px; border: 2px solid #e5e7eb; border-radius: 12px; font-size: 15px; transition: all 0.3s; }
    .form-group input:focus { outline: none; border-color: #211594; box-shadow: 0 0 0 4px rgba(33, 21, 148, 0.1); }
    .btn-primary { width: 100%; background: linear-gradient(135deg, #211594, #1a0f7a); color: white; padding: 16px; border: none; border-radius: 12px; font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s; }
    .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(33, 21, 148, 0.3); }
    .alert { padding: 16px 20px; border-radius: 12px; margin-bottom: 24px; font-size: 14px; }
    .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
    .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
    .icon-circle { width: 80px; height: 80px; background: rgba(255,255,255,0.1); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; font-size: 36px; }
</style>

<section class="auth-container">
    <div class="auth-card">
        <div class="auth-header">
            <div class="icon-circle">🔐</div>
            <h1>Forgot Password?</h1>
            <p>No worries, we'll send you reset instructions</p>
        </div>
        
        <div class="auth-body">
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($showForm): ?>
                <form method="POST" id="forgotPasswordForm" onsubmit="showForgotLoading()">
                    <div class="form-group">
                        <label>Email Address</label>
                        <input type="email" name="email" required placeholder="Enter your email address" autofocus>
                    </div>
                    
                    <button type="submit" id="submitBtn" class="btn-primary">
                        <span id="btnText">Send Reset Link</span>
                        <span id="btnSpinner" class="hidden ml-2">
                            <svg class="animate-spin h-5 w-5 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                        </span>
                    </button>
                </form>
                <script>
                    function showForgotLoading() {
                        document.getElementById('btnText').textContent = 'Sending...';
                        document.getElementById('btnSpinner').classList.remove('hidden');
                        document.getElementById('submitBtn').disabled = true;
                    }
                </script>
            <?php else: ?>
                <div class="text-center">
                    <div class="text-6xl mb-4">📧</div>
                    <p class="text-gray-600 mb-6">Check your inbox for the password reset link. <strong>The link will expire in 10 minutes.</strong></p>
                    <a href="<?php echo SITE_URL; ?>" class="inline-block bg-gradient-to-r from-primary-blue to-primary-green text-white px-8 py-3 rounded-lg font-semibold hover:opacity-90 transition">
                        Back to Home
                    </a>
                </div>
            <?php endif; ?>
            
            <div class="text-center mt-6 pt-6 border-t border-gray-100">
                <a href="<?php echo SITE_URL; ?>/login.php" class="text-primary-blue font-semibold hover:underline">
                    ← Back to Login
                </a>
            </div>
        </div>
    </div>
</section>

<?php include 'includes/footer.php'; ?>
