<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/middleware.php';
if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

// Generate secure token
function generateResetToken(): string {
    return bin2hex(random_bytes(32));
}

// Send password reset email
function sendPasswordResetEmail(string $email, string $token): bool {
    $resetLink = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]/reset_password.php?token=" . urlencode($token);
    
    $subject = "Go Legal - Password Reset Request";
    $message = "
    <html>
    <body style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;'>
        <div style='background: linear-gradient(135deg, #10b981 0%, #059669 100%); padding: 30px; border-radius: 16px; text-align: center; margin-bottom: 30px;'>
            <h1 style='color: white; margin: 0; font-size: 28px;'>Go Legal</h1>
            <p style='color: rgba(255,255,255,0.9); margin: 10px 0 0;'>Password Reset Request</p>
        </div>
        
        <div style='background: #f9fafb; padding: 30px; border-radius: 12px; border: 1px solid #e5e7eb;'>
            <h2 style='color: #1f2937; margin: 0 0 20px;'>Reset Your Password</h2>
            
            <p style='color: #6b7280; line-height: 1.6; margin-bottom: 25px;'>
                Hello,<br><br>
                We received a request to reset your password for your Go Legal account. 
                Click the button below to set a new password:
            </p>
            
            <div style='text-align: center; margin: 30px 0;'>
                <a href='$resetLink' style='background: #10b981; color: white; padding: 15px 30px; text-decoration: none; border-radius: 8px; font-weight: 600; display: inline-block;'>
                    Reset Password
                </a>
            </div>
            
            <p style='color: #6b7280; font-size: 14px; margin-bottom: 15px;'>
                Or copy and paste this link in your browser:
            </p>
            
            <p style='background: #f3f4f6; padding: 15px; border-radius: 6px; word-break: break-all; font-family: monospace; font-size: 12px; color: #374151; margin: 0 0 25px;'>
                $resetLink
            </p>
            
            <div style='border-top: 1px solid #e5e7eb; padding-top: 20px;'>
                <p style='color: #9ca3af; font-size: 12px; margin: 0; line-height: 1.5;'>
                    <strong>Security Notice:</strong> This link will expire in 1 hour for your security. 
                    If you didn't request this password reset, please ignore this email.
                </p>
            </div>
        </div>
        
        <div style='text-align: center; margin-top: 30px; color: #9ca3af; font-size: 12px;'>
            <p>© 2024 Go Legal. All rights reserved.</p>
        </div>
    </body>
    </html>";
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: Go Legal <noreply@golegal.com>" . "\r\n";
    
    return mail($email, $subject, $message, $headers);
}

// Handle forgot password request
if (is_post() && isset($_POST['email'])) {
    ensure_csrf();
    $email = trim($_POST['email']);
    
    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        set_flash('error', 'Please enter a valid email address');
        redirect('/forgot_password.php');
    }
    
    // Check if user exists
    $stmt = $pdo->prepare("SELECT id, full_name FROM users WHERE email=? AND status='active'");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    
    if ($user) {
        // Generate and store reset token
        $token = generateResetToken();
        $expires = date('c', time() + 3600); // 1 hour
        
        // Delete any existing tokens
        $pdo->prepare("DELETE FROM password_resets WHERE email=?")->execute([$email]);
        
        // Store new token
        $stmt = $pdo->prepare("INSERT INTO password_resets (email, token, expires_at, created_at) VALUES (?, ?, ?, ?)");
        $stmt->execute([$email, $token, $expires, date('c')]);
        
        // Send email
        if (sendPasswordResetEmail($email, $token)) {
            set_flash('success', 'Password reset link has been sent to your email. Please check your inbox.');
        } else {
            set_flash('error', 'Failed to send reset email. Please try again later.');
        }
    } else {
        // Don't reveal if email exists or not
        set_flash('success', 'If an account with this email exists, a password reset link has been sent.');
    }
    
    redirect('/forgot_password.php');
}

include __DIR__ . '/includes/header.php';
?>

<style>
.forgot-password-container {
    max-width: 480px;
    margin: 60px auto;
    padding: 0 20px;
}

.forgot-password-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
}

.forgot-password-header {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    padding: 40px 30px;
    text-align: center;
    color: white;
}

.forgot-password-header h1 {
    margin: 0 0 10px;
    font-size: 28px;
    font-weight: 800;
}

.forgot-password-header p {
    margin: 0;
    opacity: 0.9;
    font-size: 16px;
}

.forgot-password-body {
    padding: 40px 30px;
}

.forgot-password-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-label {
    font-weight: 600;
    color: var(--text);
    font-size: 14px;
}

.form-input {
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 15px;
    transition: all 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.btn-reset {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    padding: 16px 24px;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-reset:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px -5px rgba(16, 185, 129, 0.3);
}

.btn-reset:active {
    transform: translateY(0);
}

.back-to-login {
    text-align: center;
    margin-top: 30px;
    padding-top: 30px;
    border-top: 1px solid var(--border);
}

.back-to-login a {
    color: var(--primary);
    text-decoration: none;
    font-weight: 600;
}

.back-to-login a:hover {
    text-decoration: underline;
}

.security-notice {
    background: #f0fdf4;
    border: 1px solid #bbf7d0;
    border-radius: 10px;
    padding: 16px;
    margin-top: 20px;
}

.security-notice h3 {
    color: #166534;
    margin: 0 0 8px;
    font-size: 14px;
    font-weight: 600;
}

.security-notice p {
    color: #15803d;
    margin: 0;
    font-size: 13px;
    line-height: 1.5;
}

@media (max-width: 640px) {
    .forgot-password-container {
        margin: 40px auto;
        padding: 0 16px;
    }
    
    .forgot-password-header {
        padding: 30px 20px;
    }
    
    .forgot-password-body {
        padding: 30px 20px;
    }
}
</style>

<div class="forgot-password-container">
    <div class="forgot-password-card">
        <div class="forgot-password-header">
            <h1>Lost Your Way?</h1>
            <p>It happens to the best of us. Let's get you back into your account.</p>
        </div>
        
        <div class="forgot-password-body">
            <?php if (has_flash()): ?>
                <div class="alert alert-<?=get_flash_type()?>">
                    <?=get_flash_message()?>
                </div>
            <?php endif; ?>
            
            <form method="post" class="forgot-password-form">
                <?=csrf_field()?>
                
                <div class="form-group">
                    <label for="email" class="form-label">Email Address</label>
                    <input 
                        type="email" 
                        id="email" 
                        name="email" 
                        class="form-input" 
                        placeholder="Enter your email address"
                        required
                        autocomplete="email"
                    >
                </div>
                
                <button type="submit" class="btn-reset">
                    Send Reset Link
                </button>
            </form>
            
            <div class="security-notice">
                <h3>🔒 Security Notice</h3>
                <p>
                    For your security, the reset link will expire after 1 hour. 
                    If you don't receive an email, check your spam folder or try again.
                </p>
            </div>
            
            <div class="back-to-login">
                <a href="/login.php">← Back to Login</a>
            </div>
        </div>
    </div>
</div>

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