<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/config/config.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    
    if (empty($email)) {
        $error = 'Please enter your email';
    } else {
        try {
            $pdo = getDBConnection();
            
            // Table already exists in database
            
            // Find user
            $stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch();
            
            if ($user) {
                // Delete old codes
                $pdo->prepare("DELETE FROM password_resets WHERE email = ?")->execute([$email]);
                
                // Generate code
                $code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
                $expires = date('Y-m-d H:i:s', strtotime('+15 minutes'));
                
                // Save code
                $stmt = $pdo->prepare("INSERT INTO password_resets (user_id, email, code, expires_at) VALUES (?, ?, ?, ?)");
                $stmt->execute([$user['id'], $email, $code, $expires]);
                
                // Check if PHPMailer exists
                $autoloadPath = __DIR__ . '/vendor/autoload.php';
                if (!file_exists($autoloadPath)) {
                    $error = 'Mailer not installed. Upload vendor folder.';
                } else {
                    require_once $autoloadPath;
                    
                    // Get mail settings
                    $mailSettings = [];
                    $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key LIKE 'mail_%'");
                    while ($row = $stmt->fetch()) {
                        $mailSettings[$row['setting_key']] = $row['setting_value'];
                    }
                    
                    if (empty($mailSettings['mail_host'])) {
                        $error = 'SMTP not configured in admin settings.';
                    } else {
                        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
                        $mail->isSMTP();
                        $mail->Host = $mailSettings['mail_host'];
                        $mail->SMTPAuth = true;
                        $mail->Username = $mailSettings['mail_username'];
                        $mail->Password = $mailSettings['mail_password'];
                        $mail->Port = intval($mailSettings['mail_port']);
                        $mail->Timeout = 5; // 5 second timeout
                        $mail->SMTPKeepAlive = false;
                        
                        if (($mailSettings['mail_encryption'] ?? 'none') === 'none') {
                            $mail->SMTPSecure = '';
                            $mail->SMTPAutoTLS = false;
                        }
                        
                        $fromAddr = !empty($mailSettings['mail_from_address']) ? $mailSettings['mail_from_address'] : $mailSettings['mail_username'];
                        $fromName = !empty($mailSettings['mail_from_name']) ? $mailSettings['mail_from_name'] : SITE_NAME;
                        
                        $mail->setFrom($fromAddr, $fromName);
                        $mail->addAddress($user['email']);
                        $mail->isHTML(true);
                        $mail->Subject = 'Password Reset Code';
                        $mail->Body = '<div style="font-family:Arial;padding:20px;background:#0A1628;color:#fff;">
                            <h2 style="color:#F5A623;">Password Reset</h2>
                            <p>Hi '.$user['name'].',</p>
                            <p>Your reset code is:</p>
                            <h1 style="color:#F5A623;letter-spacing:5px;font-size:32px;">'.$code.'</h1>
                            <p>Expires in 15 minutes.</p>
                        </div>';
                        $mail->send();
                        
                        // Success - redirect
                        $_SESSION['reset_email'] = $email;
                        header('Location: verify-code.php');
                        exit;
                    }
                }
            } else {
                $error = 'Email not found';
            }
        } catch (Exception $e) {
            $error = 'Error: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password</title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:Arial,sans-serif;background:#0A1628;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
        .card{background:#0F2744;padding:30px;border-radius:12px;width:100%;max-width:400px}
        h1{color:#F5A623;text-align:center;margin-bottom:20px}
        .form-group{margin-bottom:20px}
        label{color:#fff;display:block;margin-bottom:8px}
        input{width:100%;padding:12px;background:#1E3A5F;border:1px solid #2D4A6F;border-radius:8px;color:#fff;font-size:16px}
        input:focus{outline:none;border-color:#F5A623}
        button{width:100%;padding:14px;background:#F5A623;color:#000;border:none;border-radius:8px;font-size:16px;font-weight:bold;cursor:pointer}
        button:hover{background:#FFD93D}
        .error{background:#EF4444;color:#fff;padding:10px;border-radius:8px;margin-bottom:20px;text-align:center}
        .links{text-align:center;margin-top:20px}
        .links a{color:#F5A623;text-decoration:none}
    </style>
</head>
<body>
    <div class="card">
        <h1>Forgot Password</h1>
        <?php if($error): ?><div class="error"><?php echo $error; ?></div><?php endif; ?>
        <form method="POST">
            <div class="form-group">
                <label>Email Address</label>
                <input type="email" name="email" required placeholder="Enter your email">
            </div>
            <button type="submit">Send Code</button>
        </form>
        <div class="links"><a href="login.php">Back to Login</a></div>
    </div>
</body>
</html>