<?php
session_start();
require_once 'config/database.php';

// Set the default timezone to match your server
date_default_timezone_set('UTC'); // Change this to your server's timezone if needed

// For debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if we have email and token in the URL (direct link from email)
$email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
$token = filter_input(INPUT_GET, 'token');

// Debug output
echo "<!-- Debug info: Email: " . htmlspecialchars($email ?? 'not set') . " -->";
echo "<!-- Debug info: Token: " . htmlspecialchars(substr($token ?? 'not set', 0, 10)) . "... -->";
echo "<!-- Debug info: Current time: " . date('Y-m-d H:i:s') . " -->";

$directReset = false;
if ($email && $token) {
    // Add debug output
    error_log("Reset attempt: Email=$email, Token=$token");
    
    // Validate the token
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        // First, let's check if the token exists in the database at all
        $check_stmt = $db->prepare("SELECT * FROM password_resets WHERE token = ?");
        $check_stmt->execute([$token]);
        $token_exists = $check_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($token_exists) {
            error_log("Token found in database for email: " . $token_exists['email']);
            error_log("Token expires at: " . $token_exists['expires_at']);
            error_log("Current server time: " . date('Y-m-d H:i:s'));
            
            // Now check if it matches the email and is not expired
            if ($token_exists['email'] === $email) {
                // Force the comparison to use UTC for both times
                $expires = new DateTime($token_exists['expires_at'], new DateTimeZone('UTC'));
                $now = new DateTime('now', new DateTimeZone('UTC'));
                
                error_log("Expires (UTC): " . $expires->format('Y-m-d H:i:s'));
                error_log("Now (UTC): " . $now->format('Y-m-d H:i:s'));
                
                if ($expires > $now) {
                    $directReset = true;
                    error_log("Valid reset token found. Setting directReset=true");
                } else {
                    error_log("Token is expired. Expired at: " . $token_exists['expires_at']);
                    $_SESSION['error'] = "Your password reset link has expired. Please request a new one.";
                }
            } else {
                error_log("Token exists but for a different email: " . $token_exists['email']);
                $_SESSION['error'] = "Invalid password reset link.";
            }
        } else {
            error_log("Token not found in database.");
            $_SESSION['error'] = "Invalid password reset link.";
        }
    } catch (Exception $e) {
        error_log("Error validating reset token: " . $e->getMessage());
        $_SESSION['error'] = "An error occurred. Please try again.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - First National Bank Incorporated</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/sweetalert2@11/dist/sweetalert2.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: #2563eb;
            --secondary-color: #1e40af;
            --background-color: #f0f2f5;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #2563eb, #1e40af);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

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

        .brand-logo {
            text-align: center;
            margin-bottom: 2rem;
        }

        .brand-logo img {
            height: 50px;
        }

        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 2px solid #e2e8f0;
            font-size: 0.95rem;
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: none;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--primary-color);
            border: none;
        }

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

        .back-to-login {
            text-align: center;
            margin-top: 1.5rem;
        }

        .back-to-login a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .back-to-login a:hover {
            color: var(--secondary-color);
        }

        .steps {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
        }

        .step {
            display: flex;
            align-items: center;
            margin: 0 1rem;
            color: #94a3b8;
        }

        .step.active {
            color: var(--primary-color);
        }

        .step i {
            margin-right: 0.5rem;
        }

        .info-text {
            text-align: center;
            color: #64748b;
            margin-bottom: 2rem;
        }
        
        .alert {
            margin-bottom: 1.5rem;
        }
    </style>
</head>
<body>

<div class="forgot-password-card">
    <div class="brand-logo">
        <img src="assets/images/logo.png" alt="Bank Logo">
    </div>
    
    <?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>

    <div class="steps">
        <div class="step active" id="step1">
            <i class='bx bx-envelope'></i>
            <span>Email</span>
        </div>
        <div class="step" id="step2">
            <i class='bx bx-check-circle'></i>
            <span>Verify</span>
        </div>
        <div class="step" id="step3">
            <i class='bx bx-lock-alt'></i>
            <span>Reset</span>
        </div>
    </div>

    <!-- Step 1: Email Form -->
    <div id="emailForm">
        <h4 class="text-center mb-3">Forgot Password</h4>
        <p class="info-text">Enter your email address and we'll send you a verification code.</p>

        <form onsubmit="return handleEmailSubmit(event)">
            <div class="mb-3">
                <label class="form-label">Email Address</label>
                <input type="email" class="form-control" name="email" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">Send Verification Code</button>
        </form>
    </div>

    <!-- Step 2: Verification Code Form -->
    <div id="verificationForm" style="display: none;">
        <h4 class="text-center mb-3">Enter Verification Code</h4>
        <p class="info-text">Please enter the 6-digit code sent to your email.</p>

        <form onsubmit="return handleVerificationSubmit(event)">
            <div class="mb-3">
                <label class="form-label">Verification Code</label>
                <input type="text" class="form-control" name="code" maxlength="6" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">Verify Code</button>
        </form>
    </div>

    <!-- Step 3: Reset Password Form -->
    <div id="resetForm" style="display: none;">
        <h4 class="text-center mb-3">Reset Password</h4>
        <p class="info-text">Enter your new password.</p>

        <form onsubmit="return handleResetSubmit(event)">
            <!-- Add hidden fields to store email and token -->
            <input type="hidden" id="resetEmail" name="resetEmail">
            <input type="hidden" id="resetToken" name="resetToken">
            
            <div class="mb-3">
                <label class="form-label">New Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" name="password" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword(this)">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Confirm Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" name="confirmPassword" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword(this)">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
            </div>
            <button type="submit" class="btn btn-primary w-100">Reset Password</button>
        </form>
    </div>

    <div class="back-to-login">
        <a href="index.php"><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>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Define these variables at the top
let userEmail = '';
let resetToken = '';

// Immediately execute this function when the page loads
(function() {
    <?php if ($directReset): ?>
    console.log("Direct reset detected. Email: <?php echo $email; ?>, Token: <?php echo substr($token, 0, 10); ?>...");
    userEmail = '<?php echo addslashes($email); ?>';
    resetToken = '<?php echo addslashes($token); ?>';
    
    // Use setTimeout to ensure the DOM is fully loaded
    setTimeout(function() {
        console.log("Showing reset form (step 3)");
        // Set the hidden fields
        document.getElementById('resetEmail').value = userEmail;
        document.getElementById('resetToken').value = resetToken;
        showStep(3);
    }, 500);
    <?php else: ?>
    console.log("No direct reset detected. Showing step 1.");
    <?php endif; ?>
})();

function showStep(step) {
    console.log("Showing step: " + step);
    document.querySelectorAll('.step').forEach(s => s.classList.remove('active'));
    document.getElementById(`step${step}`).classList.add('active');

    document.getElementById('emailForm').style.display = 'none';
    document.getElementById('verificationForm').style.display = 'none';
    document.getElementById('resetForm').style.display = 'none';

    switch(step) {
        case 1:
            document.getElementById('emailForm').style.display = 'block';
            break;
        case 2:
            document.getElementById('verificationForm').style.display = 'block';
            break;
        case 3:
            document.getElementById('resetForm').style.display = 'block';
            break;
    }
}

function handleEmailSubmit(event) {
    event.preventDefault();
    const email = event.target.email.value;

    Swal.fire({
        title: 'Sending Code',
        text: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('process_forgot_password.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'send_code',
            email: email
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            userEmail = email;
            Swal.fire({
                icon: 'success',
                title: 'Code Sent!',
                text: 'Please check your email for the verification code.'
            });
            showStep(2);
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred. Please try again.'
        });
    });

    return false;
}

function handleVerificationSubmit(event) {
    event.preventDefault();
    const code = event.target.code.value;

    Swal.fire({
        title: 'Verifying Code',
        text: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('process_forgot_password.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'verify_code',
            email: userEmail,
            code: code
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            resetToken = data.reset_token;
            // Set the hidden fields
            document.getElementById('resetEmail').value = userEmail;
            document.getElementById('resetToken').value = resetToken;
            showStep(3);
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred. Please try again.'
        });
    });

    return false;
}

function handleResetSubmit(event) {
    event.preventDefault();
    const password = event.target.password.value;
    const confirmPassword = event.target.confirmPassword.value;

    if (password !== confirmPassword) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Passwords do not match'
        });
        return false;
    }

    // Log the values being sent for debugging
    console.log("Submitting reset password form with:");
    console.log("Email:", userEmail);
    console.log("Token:", resetToken.substring(0, 10) + "...");

    Swal.fire({
        title: 'Resetting Password',
        text: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    fetch('process_forgot_password.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'reset_password',
            email: userEmail,
            reset_token: resetToken,
            password: password
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log("Reset password response:", data);
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Password Reset!',
                text: 'Your password has been reset successfully.',
                confirmButtonText: 'Go to Login'
            }).then(() => {
                window.location.href = 'index.php';
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.message || 'An error occurred while resetting your password.'
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred. Please try again.'
        });
    });

    return false;
}

function togglePassword(button) {
    const input = button.previousElementSibling;
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.replace('bx-show', 'bx-hide');
    } else {
        input.type = 'password';
        icon.classList.replace('bx-hide', 'bx-show');
    }
}
</script>

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
