<?php
session_start();
include 'config/db.php';

$error = '';
$success = '';
$step = 'request';

// Create password_resets table if not exists
$conn->query("CREATE TABLE IF NOT EXISTS password_resets (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(100) NOT NULL,
    token VARCHAR(255) NOT NULL,
    expires_at DATETIME NOT NULL,
    used TINYINT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Process password reset request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['request_reset'])) {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    
    // Check if email exists
    $result = $conn->query("SELECT * FROM users WHERE email='$email'");
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
        // Generate unique token
        $token = bin2hex(random_bytes(32));
        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        // Delete old tokens for this email
        $conn->query("DELETE FROM password_resets WHERE email='$email'");
        
        // Insert new token
        $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $email, $token, $expiry);
        $stmt->execute();
        $stmt->close();
        
        // Create reset link
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $reset_link = $protocol . $host . $uri . "/reset_password.php?token=" . $token;
        
        // Simple email content
        $email_body = "
        <html>
        <head><title>Password Reset</title></head>
        <body>
            <h2>Password Reset Request</h2>
            <p>Dear " . htmlspecialchars($user['name']) . ",</p>
            <p>Click the link below to reset your password:</p>
            <p><a href='" . $reset_link . "'>Reset Password</a></p>
            <p>Or copy this link: " . $reset_link . "</p>
            <p>This link expires in 1 hour.</p>
            <p>If you didn't request this, ignore this email.</p>
        </body>
        </html>
        ";
        
        // Simple mail function
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: noreply@" . $_SERVER['HTTP_HOST'] . "\r\n";
        
        if (mail($email, "Password Reset Request", $email_body, $headers)) {
            $success = "✅ Password reset link sent to your email!";
            $step = 'sent';
        } else {
            // Show link directly if email fails
            $success = "⚠️ Email sending failed. Use this link:<br>
                        <a href='$reset_link' target='_blank'>$reset_link</a>";
            $step = 'sent';
        }
    } else {
        $error = "❌ Email not found!";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - BMYA-SHELDANG</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Poppins', sans-serif;
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container { max-width: 450px; width: 100%; margin: auto; }
        .card {
            background: white;
            border-radius: 20px;
            padding: 35px 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            position: relative;
        }
        .back-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            background: #f0f0f0;
            width: 35px;
            height: 35px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #666;
        }
        .back-btn:hover { background: #667eea; color: white; }
        .logo-section { text-align: center; margin-bottom: 25px; }
        .logo-image {
            width: 70px;
            height: 70px;
            object-fit: contain;
            margin: 0 auto 15px;
            display: block;
        }
        .logo-section h2 { font-size: 1.5rem; color: #333; margin-bottom: 5px; }
        .logo-section p { color: #666; font-size: 0.85rem; }
        .alert {
            padding: 12px 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.85rem;
        }
        .alert-error { background: #fee2e2; color: #991b1b; border-left: 4px solid #dc2626; }
        .alert-success { background: #d1fae5; color: #065f46; border-left: 4px solid #10b981; }
        .form-group { margin-bottom: 20px; }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        .form-group label i { color: #667eea; margin-right: 5px; }
        .input-wrapper { position: relative; }
        .input-wrapper i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }
        .input-wrapper input {
            width: 100%;
            padding: 12px 12px 12px 42px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 0.9rem;
            font-family: 'Poppins', sans-serif;
            outline: none;
        }
        .input-wrapper input:focus { border-color: #667eea; box-shadow: 0 0 0 2px rgba(102,126,234,0.1); }
        .btn-submit {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.3); }
        .btn-login {
            display: block;
            text-align: center;
            margin-top: 20px;
            color: #667eea;
            text-decoration: none;
            font-size: 0.85rem;
        }
        .btn-login:hover { text-decoration: underline; }
        .info-text {
            background: #e3f2fd;
            padding: 10px;
            border-radius: 8px;
            font-size: 0.7rem;
            color: #1976d2;
            text-align: center;
            margin-top: 15px;
        }
        @media (max-width: 480px) {
            .card { padding: 30px 20px; }
            .logo-image { width: 55px; height: 55px; }
            .logo-section h2 { font-size: 1.3rem; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <a href="login.php" class="back-btn">
                <i class="fas fa-arrow-left"></i>
            </a>
            <div class="logo-section">
                <img src="https://bmyouth.org/sheldang/assets/logo.png" class="logo-image" 
                     onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 100 100%27%3E%3Ccircle cx=%2750%27 cy=%2750%27 r=%2745%27 fill=%27%23667eea%27/%3E%3Ctext x=%2750%27 y=%2770%27 text-anchor=%27middle%27 fill=%27white%27 font-size=%2740%27%3EB%3C/text%3E%3C/svg%3E'">
                <h2>Forgot Password?</h2>
                <p>Enter your email to reset password</p>
            </div>

            <?php if($error): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?= $error ?></span>
            </div>
            <?php endif; ?>

            <?php if($success): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?= $success ?></span>
            </div>
            <div style="text-align: center; margin-top: 15px;">
                <a href="login.php" class="btn-submit" style="display: inline-block; width: auto; padding: 8px 20px; background: #6c757d;">
                    Back to Login
                </a>
            </div>
            <?php endif; ?>

            <?php if($step == 'request'): ?>
            <form method="POST">
                <div class="form-group">
                    <label><i class="fas fa-envelope"></i> Email Address</label>
                    <div class="input-wrapper">
                        <i class="fas fa-envelope"></i>
                        <input type="email" name="email" placeholder="Enter your registered email" required>
                    </div>
                </div>
                <button type="submit" name="request_reset" class="btn-submit">
                    <i class="fas fa-paper-plane"></i> Send Reset Link
                </button>
            </form>
            <div class="info-text">
                <i class="fas fa-info-circle"></i> We'll send a password reset link to your email. Link expires in 1 hour.
            </div>
            <a href="login.php" class="btn-login">
                <i class="fas fa-arrow-left"></i> Back to Login
            </a>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>