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

// Set the default timezone
date_default_timezone_set('UTC');

// Get email and token from URL
$email = filter_input(INPUT_GET, 'email', FILTER_VALIDATE_EMAIL);
$token = filter_input(INPUT_GET, 'token');

// Initialize variables
$message = '';
$messageType = 'danger';
$validToken = false;
$resetComplete = false;

// Generate CSRF token if it doesn't exist
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Validate token if email and token are provided
if ($email && $token) {
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        // Check if token exists and is valid
        $stmt = $db->prepare("SELECT * FROM password_resets WHERE email = ? AND token = ?");
        $stmt->execute([$email, $token]);
        $reset = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($reset) {
            // Token exists, now check if it's expired
            $expires = new DateTime($reset['expires_at'], new DateTimeZone('UTC'));
            $now = new DateTime('now', new DateTimeZone('UTC'));
            
            if ($expires > $now) {
                $validToken = true;
            } else {
                $message = "Your password reset link has expired. Please request a new one.";
            }
        } else {
            $message = "Invalid password reset link. Please request a new one.";
        }
    } catch (Exception $e) {
        $message = "An error occurred. Please try again.";
        error_log("Error validating reset token: " . $e->getMessage());
    }
} else {
    $message = "Invalid request. Please use the link from your email.";
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $validToken) {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $message = "Invalid form submission. Please try again.";
    } else {
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm'] ?? '';
        
        // Validate password
        if (strlen($password) < 8) {
            $message = "Password must be at least 8 characters long.";
        } elseif (!preg_match('/[A-Z]/', $password)) {
            $message = "Password must contain at least one uppercase letter.";
        } elseif (!preg_match('/[a-z]/', $password)) {
            $message = "Password must contain at least one lowercase letter.";
        } elseif (!preg_match('/[0-9]/', $password)) {
            $message = "Password must contain at least one number.";
        } elseif ($password !== $confirm) {
            $message = "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 = ?");
                $result = $stmt->execute([$hashedPassword, $email]);
                
                if ($result) {
                    // Delete the used reset token
                    $stmt = $db->prepare("DELETE FROM password_resets WHERE email = ?");
                    $stmt->execute([$email]);
                    
                    $message = "Your password has been reset successfully!";
                    $messageType = "success";
                    $resetComplete = true;
                    
                    // Log the successful password reset
                    error_log("Password reset successful for email: $email");
                } else {
                    $message = "Failed to update password. Please try again.";
                    error_log("Failed to update password for email: $email");
                }
            } catch (Exception $e) {
                $message = "An error occurred while resetting your password. Please try again.";
                error_log("Error resetting password: " . $e->getMessage());
            }
        }
    }
}

// Bank branding variables - you can define these in your config file
$bankName = defined('BANK_NAME') ? BANK_NAME : 'First National Bank Incorporated';
$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>Reset Password - <?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: 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);
        }
        
        .password-requirements {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 0.9rem;
        }
        
        .password-requirements ul {
            margin-bottom: 0;
            padding-left: 20px;
        }
        
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 5px;
            transition: all 0.3s ease;
        }
    </style>
</head>
<body>

<div class="reset-card">
    <div class="brand-logo">
        <img src="<?php echo htmlspecialchars($bankLogo); ?>" alt="<?php echo htmlspecialchars($bankName); ?> Logo">
    </div>

    <h4 class="text-center mb-4">Reset Your Password</h4>
    
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>" role="alert">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
    
    <?php if ($resetComplete): ?>
        <div class="text-center mt-4">
            <p>You can now log in with your new password.</p>
            <a href="login.php" class="btn btn-primary">Go to Login</a>
        </div>
    <?php elseif ($validToken): ?>
        <div class="password-requirements mb-4">
            <h6>Password Requirements:</h6>
            <ul>
                <li>At least 8 characters long</li>
                <li>At least one uppercase letter</li>
                <li>At least one lowercase letter</li>
                <li>At least one number</li>
            </ul>
        </div>
        
        <form method="post" id="resetForm">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            
            <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 minlength="8">
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('password')">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
                <div class="password-strength" id="passwordStrength"></div>
            </div>
            
            <div class="mb-4">
                <label class="form-label">Confirm Password</label>
                <div class="input-group">
                    <input type="password" class="form-control" name="confirm" id="confirm" required minlength="8">
                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirm')">
                        <i class='bx bx-show'></i>
                    </button>
                </div>
            </div>
            
            <button type="submit" class="btn btn-primary w-100">Reset Password</button>
        </form>
    <?php else: ?>
        <div class="text-center mt-4">
            <p>The password reset link is invalid or has expired.</p>
            <a href="forgot-password.php" class="btn btn-primary">Request New Reset Link</a>
        </div>
    <?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>
// Toggle password visibility
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');
    }
}

// Password strength meter
document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.getElementById('password');
    const confirmInput = document.getElementById('confirm');
    const strengthMeter = document.getElementById('passwordStrength');
    const form = document.getElementById('resetForm');
    
    if (passwordInput && strengthMeter) {
        passwordInput.addEventListener('input', function() {
            const password = this.value;
            let strength = 0;
            
            // Calculate password strength
            if (password.length >= 8) strength += 25;
            if (password.match(/[A-Z]/)) strength += 25;
            if (password.match(/[a-z]/)) strength += 25;
            if (password.match(/[0-9]/)) strength += 25;
            
            // Update strength meter
            strengthMeter.style.width = strength + '%';
            
            // Set color based on strength
            if (strength < 50) {
                strengthMeter.style.backgroundColor = '#dc3545'; // Red
            } else if (strength < 75) {
                strengthMeter.style.backgroundColor = '#ffc107'; // Yellow
            } else {
                strengthMeter.style.backgroundColor = '#198754'; // Green
            }
        });
    }
    
    if (form && passwordInput && confirmInput) {
        form.addEventListener('submit', function(e) {
            if (passwordInput.value !== confirmInput.value) {
                e.preventDefault();
                alert('Passwords do not match!');
            }
        });
    }
});
</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>
