<?php
session_start();
require_once 'config/database.php';
require_once 'includes/email_templates.php'; // Include email templates

// Check if user is already fully logged in
if (isset($_SESSION['user_id']) && isset($_SESSION['auth_step']) && $_SESSION['auth_step'] === 'completed') {
    header('Location: customer/dashboard.php');
    exit;
}

// Initialize variables
$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the email from the form
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    
    if (!$email) {
        $message = 'Please enter a valid email address.';
        $messageType = 'danger';
    } else {
        try {
            require_once 'config/database.php';
            $database = new Database();
            $db = $database->getConnection();
            
            // Check if the email exists in the database
            $stmt = $db->prepare("SELECT id, first_name, last_name FROM users WHERE email = ? AND status = 'active'");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // Generate a unique reset token
                $token = bin2hex(random_bytes(32));
                $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Store the token in the database
                $resetStmt = $db->prepare("INSERT INTO pin_reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
                $resetStmt->execute([$user['id'], $token, $expires]);
                
                // Generate the reset link
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
                $host = $_SERVER['HTTP_HOST'];
                $resetLink = "$protocol://$host/reset-pin.php?token=" . $token;
                
                // Log the reset link for development purposes
                error_log("PIN Reset Link for {$email}: {$resetLink}");
                
                // Send email with reset link
                $userName = $user['first_name'] . ' ' . $user['last_name'];
                $emailSent = false;
                
                // Try to use the email template function if it exists
                if (function_exists('sendPinResetEmail')) {
                    $emailSent = sendPinResetEmail($email, $userName, $token);
                } else if (function_exists('generatePinResetEmail') && function_exists('sendEmailByBestMethod')) {
                    // Generate email content
                    $emailBody = generatePinResetEmail($userName, $resetLink, $email);
                    
                    // Email subject
                    $subject = "PIN Reset Request - " . (defined('BANK_NAME') ? BANK_NAME : 'Ocean Bank Cooperation');
                    
                    // Send the email using the best available method
                    $emailSent = sendEmailByBestMethod($email, $subject, $emailBody);
                } else {
                    // Fallback to a simple email if no template functions exist
                    $subject = "PIN Reset Request";
                    $message = "Hello $userName,\n\n";
                    $message .= "You have requested to reset your PIN. Please click the link below to reset your PIN:\n\n";
                    $message .= "$resetLink\n\n";
                    $message .= "This link will expire in 1 hour.\n\n";
                    $message .= "If you did not request a PIN reset, please ignore this email.\n\n";
                    $message .= "Regards,\nThe Banking Team";
                    
                    $headers = "From: " . (defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : 'Ocean Bank Cooperation') . 
                               " <" . (defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'noreply@example.com') . ">\r\n";
                    
                    $emailSent = mail($email, $subject, $message, $headers);
                }
                
                if ($emailSent) {
                    $message = "PIN reset instructions have been sent to your email address. Please check your inbox.";
                    $messageType = 'success';
                } else {
                    error_log("Failed to send PIN reset email to: $email");
                    $message = "There was an issue sending the email. Please try again later.";
                    $messageType = 'danger';
                }
                
            } else {
                // Don't reveal if the email exists or not (security best practice)
                $message = "If your email is registered, you will receive PIN reset instructions shortly.";
                $messageType = 'info';
                
                // Log that the email was not found
                error_log("PIN reset requested for non-existent email: $email");
            }
        } catch (Exception $e) {
            error_log("Forgot PIN Error: " . $e->getMessage());
            $message = "An error occurred. Please try again later.";
            $messageType = 'danger';
        }
    }
}

// Bank branding variables - you can define these in your config file
$bankName = defined('BANK_NAME') ? BANK_NAME : 'Ocean Bank Cooperation';
$bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'assets/images/logo.png';
$primaryColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#2563eb';
$secondaryColor = defined('BANK_SECONDARY_COLOR') ? BANK_SECONDARY_COLOR : '#1e40af';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot PIN - <?php echo htmlspecialchars($bankName); ?></title>
    
    <!-- CSS Dependencies -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.0.7/css/boxicons.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">

    <style>
        :root {
            --primary-color: <?php echo $primaryColor; ?>;
            --secondary-color: <?php echo $secondaryColor; ?>;
            --background-color: #f0f2f5;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }

        .forgot-pin-container {
            background: white;
            border-radius: 20px;
            padding: 2rem;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 400px;
            width: 100%;
        }

        .icon-container {
            width: 70px;
            height: 70px;
            margin: 0 auto 1.5rem;
            background-color: #f0f9ff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .icon-container i {
            font-size: 2rem;
            color: var(--primary-color);
        }

        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(37, 99, 235, 0.1);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            transform: translateY(-2px);
        }

        .btn-link {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-link:hover {
            color: var(--secondary-color);
            text-decoration: underline;
        }
    </style>
</head>
<body>

<div class="forgot-pin-container">
    <div class="text-center mb-4">
        <div class="icon-container">
            <i class='bx bx-lock-open'></i>
        </div>
        <h4>Forgot Your PIN?</h4>
        <p class="text-muted">Enter your email address to receive PIN reset instructions</p>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
            <?php echo $message; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <form method="POST" action="forgot-pin.php">
        <div class="mb-3">
            <label for="email" class="form-label">Email Address</label>
            <input type="email" class="form-control" id="email" name="email" placeholder="Enter your registered email" required>
        </div>
        <div class="d-grid gap-2 mb-3">
            <button type="submit" class="btn btn-primary">Send Reset Instructions</button>
        </div>
    </form>

    <div class="text-center mt-3">
        <a href="login.php" class="btn-link">
            <i class='bx bx-arrow-back'></i> Back to Login
        </a>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
