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

// 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
$email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
$token = filter_input(INPUT_GET, 'token');

$validToken = false;
$errorMessage = '';

if ($email && $token) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        // Check if token is valid
        $stmt = $db->prepare("
            SELECT * FROM password_resets 
            WHERE email = ? AND token = ? AND expires_at > NOW()
        ");
        $stmt->execute([$email, $token]);
        $reset = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($reset) {
            $validToken = true;
        } else {
            // Check if token exists but is expired
            $stmt = $db->prepare("
                SELECT * FROM password_resets 
                WHERE email = ? AND token = ?
            ");
            $stmt->execute([$email, $token]);
            $expired = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($expired) {
                $errorMessage = "Your password reset link has expired. Please request a new one.";
                error_log("Token expired for $email. Expired at: " . $expired['expires_at']);
            } else {
                $errorMessage = "Invalid password reset link.";
                error_log("Token not found for $email");
                
                // Check if token exists for any email
                $stmt = $db->prepare("SELECT * FROM password_resets WHERE token = ?");
                $stmt->execute([$token]);
                $token_exists = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($token_exists) {
                    error_log("Token exists but for email: " . $token_exists['email']);
                }
            }
        }
    } catch (Exception $e) {
        $errorMessage = "An error occurred. Please try again.";
        error_log("Error validating reset token: " . $e->getMessage());
    }
} else {
    $errorMessage = "Invalid request. Please use the link from your email.";
    error_log("Missing email or token in reset password request");
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $validToken) {
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    if (strlen($password) < 8) {
        $errorMessage = "Password must be at least 8 characters long.";
    } elseif ($password !== $confirmPassword) {
        $errorMessage = "Passwords do not match.";
    } else {
        try {
            $database = new Database();
            $db = $database->getConnection();
            
            // Update user's password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("UPDATE users SET password = ? WHERE email = ?");
            $stmt->execute([$hashedPassword, $email]);
            
            // Delete the used reset token
            $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
            $stmt->execute([$email]);
            
            // Set success message and redirect
            $_SESSION['success'] = "Your password has been reset successfully. You can now log in with your new password.";
            header("Location: login.php");
            exit;
        } catch (Exception $e) {
            $errorMessage = "An error occurred while resetting your password. Please try again.";
            error_log("Error resetting password: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset 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/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;
        }

        .reset-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);
        }
    </style>
</head>
<body>

<div class="reset-card">
    <div class="brand-logo">
        <img src="assets/images/logo.png" alt="Bank Logo">
    </div>

    <?php if (!$validToken): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo htmlspecialchars($errorMessage); ?>
        </div>
        <div class="text-center mt-4">
            <a href="forgot-password.php" class="btn btn-primary">Request New Reset Link</a>
        </div>
    <?php else: ?>
        <h4 class="text-center mb-4">Reset Your Password</h4>
        
        <?php if (!empty($errorMessage)): ?>
            <div class="alert alert-danger" role="alert">
                <?php echo htmlspecialchars($errorMessage); ?>
            </div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="mb-3">
                <label class="form-label">New Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" name="password" id="password" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('password')">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
                <small class="text-muted">Password must be at least 8 characters long</small>
            </div>
            
            <div class="mb-4">
                <label class="form-label">Confirm Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" name="confirm_password" id="confirm_password" required>
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirm_password')">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary w-100">Reset Password</button>
        </form>
    <?php endif; ?>

    <div class="back-to-login">
        <a href="login.php"><i class='bx bx-arrow-back'></i> Back to Login</a>
    </div>
</div>

<script>
function togglePassword(id) {
    const input = document.getElementById(id);
    const icon = input.nextElementSibling.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>
