<?php
session_start();
include 'layouts/dbconn.php';

error_reporting(E_ALL);
ini_set('log_errors', 1);

// Set PHP timezone to EAT
date_default_timezone_set('Africa/Nairobi');

// Set MySQL session timezone to EAT
$conn->query("SET time_zone = '+03:00';");

// Validate token
$token = $_GET['token'] ?? '';
$valid = false;
$error = '';

if ($token) {
    // Check if token exists and is not expired or used
    $sql = "SELECT pr.*, u.username, u.email, u.full_name,
       CONVERT_TZ(pr.expires_at, '+00:00', '+03:00') AS expires_at_eat,
       CONVERT_TZ(NOW(), '+00:00', '+03:00') AS now_eat
        FROM password_resets pr
        LEFT JOIN users u ON pr.user_id = u.user_id
        WHERE pr.token = ?;";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $token);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 1) {
        $reset = $result->fetch_assoc();
        $valid = true;

        // Debugging: Log token and expiry details
        error_log("Token: $token");
        error_log("Expires At (EAT): " . $reset['expires_at_eat']);
        error_log("Current Time (EAT): " . date('Y-m-d H:i:s'));
        error_log("Token Valid: Yes");
    } else {
        // Check if token exists but is expired or already used
        $sql = "SELECT CONVERT_TZ(expires_at, '+00:00', '+03:00') AS expires_at_eat,
                       used_at
                FROM password_resets 
                WHERE token = ? 
                LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('s', $token);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $reset = $result->fetch_assoc();
            $expires_at_eat = strtotime($reset['expires_at_eat']);
            $now_eat = time(); // PHP time is already set to EAT

            if ($expires_at_eat < $now_eat) {
                $error = 'This password reset link has expired. Please request a new one.';
            } elseif ($reset['used_at'] !== null) {
                $error = 'This password reset link has already been used. Please request a new one.';
            } else {
                $error = 'Invalid password reset link. Please check the URL or request a new link.';
            }

            // Debugging: Log token and error details
            error_log("Token: $token");
            error_log("Expires At (EAT): " . $reset['expires_at_eat']);
            error_log("Current Time (EAT): " . date('Y-m-d H:i:s'));
            error_log("Token Valid: No");
            error_log("Error: $error");
        } else {
            $error = 'Invalid password reset link. Please check the URL or request a new link.';
            error_log("Token: $token");
            error_log("Error: Token not found in database");
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>
<!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 getenv('APP_NAME') ?: 'MediSure360'; ?></title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div class="auth-page-wrapper pt-5">

        <div class="auth-page-content">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center mt-sm-5 mb-4 text-white-50">
                            <div>
                                <a href="index.php" class="d-inline-block auth-logo">
                                    <img src="assets/images/med360_logo.png" alt="" height="50">
                                </a>
                            </div>
                            <p class="mt-3 fs-15">Health Insurance Management System</p>
                        </div>
                    </div>
                </div>

                <div class="row justify-content-center">
                    <div class="col-md-8 col-lg-6 col-xl-5">
                        <div class="card mt-4">
                            <div class="card-body p-4">
                                <div class="text-center mt-2">
                                    <h5 class="text-primary">Reset Password</h5>
                                    <?php if ($valid): ?>
                                        <p class="text-muted">Hello <?php echo htmlspecialchars($reset['full_name']); ?>, please enter your new password below.</p>
                                    <?php endif; ?>
                                </div>

                                <div class="p-2">
                                    <?php if ($valid): ?>
                                        <form id="resetPasswordForm">
                                            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                                            
                                            <div class="mb-3">
                                                <label class="form-label" for="password">New Password</label>
                                                <div class="position-relative auth-pass-inputgroup">
                                                    <input type="password" class="form-control pe-5" 
                                                           placeholder="Enter new password" id="password" name="password"
                                                           required minlength="8">
                                                    <button class="btn btn-link position-absolute end-0 top-0 text-decoration-none text-muted password-addon" 
                                                            type="button" id="password-addon">
                                                        <i class="ri-eye-fill align-middle"></i>
                                                    </button>
                                                </div>
                                                <div class="mt-1">
                                                    <small class="text-muted">
                                                        Password must be at least 8 characters long and contain:
                                                        <ul class="mb-0 ps-3">
                                                            <li>At least one uppercase letter</li>
                                                            <li>At least one lowercase letter</li>
                                                            <li>At least one number</li>
                                                            <li>At least one special character</li>
                                                        </ul>
                                                    </small>
                                                </div>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label" for="confirm_password">Confirm Password</label>
                                                <div class="position-relative auth-pass-inputgroup">
                                                    <input type="password" class="form-control pe-5" 
                                                           placeholder="Confirm new password" id="confirm_password" 
                                                           name="confirm_password" required minlength="8">
                                                    <button class="btn btn-link position-absolute end-0 top-0 text-decoration-none text-muted password-addon" 
                                                            type="button" id="confirm-password-addon">
                                                        <i class="ri-eye-fill align-middle"></i>
                                                    </button>
                                                </div>
                                            </div>

                                            <div class="mt-4">
                                                <button class="btn btn-primary w-100" type="submit">Reset Password</button>
                                            </div>
                                        </form>
                                    <?php else: ?>
                                        <div class="text-center">
                                            <div class="avatar-lg mx-auto">
                                                <div class="avatar-title bg-light text-danger display-5 rounded-circle">
                                                    <i class="ri-error-warning-line"></i>
                                                </div>
                                            </div>
                                            <div class="mt-4">
                                                <h4 class="text-danger">Invalid Link</h4>
                                                <p class="text-muted"><?php echo $error; ?></p>
                                                <div class="mt-4">
                                                    <a href="forgot_password.php" class="btn btn-primary w-100">
                                                        Request New Link
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <div class="mt-4 text-center">
                            <p class="mb-0">Wait, I remember my password... <a href="login.php" class="fw-semibold text-primary text-decoration-underline">Click here</a></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <?php echo date('Y'); ?> <?php echo getenv('APP_NAME') ?: 'MediSure360'; ?>.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
    </div>

    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script src="assets/libs/feather-icons/feather.min.js"></script>
    <script src="assets/js/pages/plugins/lord-icon-2.1.0.js"></script>
    <script src="assets/libs/particles.js/particles.js"></script>
    <script src="assets/js/pages/particles.app.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/pages/password-addon.init.js"></script>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        <?php if ($valid): ?>
        document.getElementById('resetPasswordForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            // Validate password
            const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$/;
            if (!passwordRegex.test(password)) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Password',
                    text: 'Password must meet all the requirements listed.'
                });
                return;
            }
            
            // Check if passwords match
            if (password !== confirmPassword) {
                Swal.fire({
                    icon: 'error',
                    title: 'Passwords Do Not Match',
                    text: 'Please make sure both passwords are identical.'
                });
                return;
            }
            
            // Show loading state
            Swal.fire({
                title: 'Processing',
                text: 'Please wait while we update your password...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            // Send request to backend
            fetch('process_reset_password.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `token=${encodeURIComponent(token)}&password=${encodeURIComponent(password)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: 'Your password has been reset successfully. You can now login with your new password.',
                        confirmButtonText: 'Login Now'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = 'login.php';
                        }
                    });
                } else {
                    throw new Error(data.error || 'Failed to reset password');
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        });

        // Password visibility toggle
        document.querySelectorAll('.password-addon').forEach(button => {
            button.addEventListener('click', function() {
                const input = this.previousElementSibling;
                const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                input.setAttribute('type', type);
                this.querySelector('i').className = `ri-${type === 'password' ? 'eye-fill' : 'eye-off-fill'} align-middle`;
            });
        });
        <?php endif; ?>
    </script>
</body>
</html>