<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Reset Password Page
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/config/constants.php';
require_once dirname(__DIR__) . '/config/database.php';
require_once dirname(__DIR__) . '/config/helpers.php';
require_once dirname(__DIR__) . '/config/auth.php';
require_once dirname(__DIR__) . '/config/csrf.php';

// Redirect if already logged in
if (is_logged_in()) {
    redirect('dashboard.php');
}

// Get token from URL
$token = $_GET['token'] ?? '';

// Validate token
$user_id = validate_password_reset_token($token);
$token_valid = ($user_id !== false);

// Handle form submission
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $token = $_POST['token'] ?? '';
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate token again
        $user_id = validate_password_reset_token($token);
        
        if (!$user_id) {
            $error = 'Invalid or expired reset token. Please request a new password reset.';
        } elseif (empty($password)) {
            $error = 'Please enter a new password';
        } elseif (strlen($password) < 8) {
            $error = 'Password must be at least 8 characters long';
        } elseif (!preg_match(REGEX_PASSWORD, $password)) {
            $error = 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character';
        } elseif ($password !== $confirm_password) {
            $error = 'Passwords do not match';
        } else {
            // Reset password
            $result = reset_password_with_token($token, $password);
            
            if ($result) {
                $message = 'Your password has been successfully reset. You can now login with your new password.';
                
                // Clear token from URL
                $token = '';
                
                // Log the action
                audit_log($user_id, 'password_reset_complete', 'users', $user_id);
            } else {
                $error = 'Failed to reset password. Please try again.';
            }
        }
    }
}

// Set page title
$page_title = 'Reset Password';
?>

<!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 APP_NAME; ?></title>
    
    <!-- CSRF Meta Tags -->
    <?php echo csrf_meta_tags(); ?>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Custom CSS -->
    <link rel="stylesheet" href="<?php echo assets_url('css/style.css'); ?>?v=<?php echo APP_VERSION; ?>">
    
    <style>
        :root {
            --primary-color: #007bff;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .reset-container {
            width: 100%;
            max-width: 450px;
            animation: fadeIn 0.5s ease;
        }
        
        .reset-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .reset-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
        }
        
        .reset-header {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .reset-header h1 {
            margin: 0;
            font-size: 2rem;
            font-weight: 600;
        }
        
        .reset-header p {
            margin: 0.5rem 0 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }
        
        .reset-body {
            padding: 2rem;
        }
        
        .resort-logo {
            width: 100px;
            height: 100px;
            background: white;
            border-radius: 50%;
            margin: -70px auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .resort-logo img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
            position: relative;
        }
        
        .form-group i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--primary-color);
            font-size: 1.1rem;
            z-index: 10;
        }
        
        .form-control {
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            border: 2px solid #e0e0e0;
            border-radius: 50px;
            font-size: 1rem;
            transition: all 0.3s ease;
            height: auto;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
            outline: none;
        }
        
        .form-control.is-invalid {
            border-color: var(--danger-color);
        }
        
        .invalid-feedback {
            display: block;
            margin-top: 0.5rem;
            padding-left: 1rem;
            color: var(--danger-color);
            font-size: 0.875rem;
        }
        
        .password-strength {
            margin-top: 0.5rem;
            padding: 0.5rem;
            border-radius: 50px;
            background: #f8f9fa;
            font-size: 0.85rem;
        }
        
        .strength-bar {
            height: 5px;
            border-radius: 5px;
            margin-top: 0.5rem;
            transition: all 0.3s ease;
        }
        
        .strength-weak {
            background: var(--danger-color);
            width: 25%;
        }
        
        .strength-medium {
            background: #ffc107;
            width: 50%;
        }
        
        .strength-strong {
            background: #17a2b8;
            width: 75%;
        }
        
        .strength-very-strong {
            background: var(--success-color);
            width: 100%;
        }
        
        .btn-reset {
            background: linear-gradient(135deg, var(--primary-color), #0056b3);
            border: none;
            border-radius: 50px;
            padding: 0.75rem;
            font-size: 1.1rem;
            font-weight: 600;
            color: white;
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            margin-bottom: 1rem;
        }
        
        .btn-reset:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.4);
        }
        
        .btn-reset:disabled {
            opacity: 0.7;
            cursor: not-allowed;
        }
        
        .btn-reset .spinner-border {
            width: 1.2rem;
            height: 1.2rem;
            margin-right: 0.5rem;
        }
        
        .btn-login {
            background: transparent;
            border: 2px solid var(--primary-color);
            border-radius: 50px;
            padding: 0.75rem;
            font-size: 1rem;
            font-weight: 600;
            color: var(--primary-color);
            width: 100%;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-login:hover {
            background: var(--primary-color);
            color: white;
            text-decoration: none;
        }
        
        .alert {
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            margin-bottom: 1.5rem;
            border: none;
            animation: slideIn 0.3s ease;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .alert-warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .requirements-list {
            margin-top: 1rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 10px;
            font-size: 0.85rem;
        }
        
        .requirements-list ul {
            margin: 0.5rem 0 0;
            padding-left: 1.5rem;
        }
        
        .requirements-list li {
            margin-bottom: 0.25rem;
            color: #6c757d;
        }
        
        .requirements-list li.valid {
            color: var(--success-color);
        }
        
        .requirements-list li i {
            margin-right: 0.5rem;
        }
        
        .login-footer {
            margin-top: 2rem;
            text-align: center;
            color: white;
            font-size: 0.9rem;
        }
        
        .login-footer a {
            color: white;
            text-decoration: none;
            font-weight: 600;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .developer-credit {
            margin-top: 2rem;
            font-size: 0.85rem;
            color: rgba(255,255,255,0.7);
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .reset-header {
                padding: 1.5rem;
            }
            
            .reset-header h1 {
                font-size: 1.5rem;
            }
            
            .reset-body {
                padding: 1.5rem;
            }
            
            .resort-logo {
                width: 80px;
                height: 80px;
                margin-top: -60px;
            }
            
            .resort-logo img {
                width: 60px;
                height: 60px;
            }
            
            .form-control {
                padding: 0.6rem 1rem 0.6rem 2.2rem;
                font-size: 0.95rem;
            }
            
            .btn-reset, .btn-login {
                padding: 0.6rem;
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-card">
            <div class="reset-header">
                <h1>Reset Password</h1>
                <p>Create a new password</p>
            </div>
            
            <div class="reset-body">
                <!-- Resort Logo -->
                <div class="resort-logo">
                    <img src="<?php echo assets_url('img/logo.png'); ?>" alt="Ruhondo Beach Resort">
                </div>
                
                <?php if (!$token_valid && !$message): ?>
                    <!-- Invalid Token -->
                    <div class="alert alert-warning" role="alert">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        Invalid or expired password reset link. Please request a new one.
                    </div>
                    
                    <div class="text-center">
                        <a href="<?php echo base_url('forgot-password.php'); ?>" class="btn-login">
                            <i class="fas fa-key mr-2"></i> Request New Link
                        </a>
                    </div>
                    
                <?php elseif ($message): ?>
                    <!-- Success Message -->
                    <div class="alert alert-success" role="alert">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo escape_html($message); ?>
                    </div>
                    
                    <div class="text-center">
                        <a href="<?php echo base_url('login.php'); ?>" class="btn-login">
                            <i class="fas fa-sign-in-alt mr-2"></i> Go to Login
                        </a>
                    </div>
                    
                <?php else: ?>
                    <!-- Error Alert -->
                    <?php if ($error): ?>
                        <div class="alert alert-danger" role="alert">
                            <i class="fas fa-exclamation-circle mr-2"></i>
                            <?php echo escape_html($error); ?>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Reset Form -->
                    <form method="POST" action="<?php echo base_url('reset-password.php?token=' . urlencode($token)); ?>" id="resetForm">
                        <?php echo csrf_field(); ?>
                        
                        <input type="hidden" name="token" value="<?php echo escape_html($token); ?>">
                        
                        <div class="form-group">
                            <i class="fas fa-lock"></i>
                            <input type="password" 
                                   class="form-control" 
                                   id="password" 
                                   name="password" 
                                   placeholder="New Password"
                                   required 
                                   autofocus>
                        </div>
                        
                        <div class="password-strength mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span>Password Strength:</span>
                                <span id="strengthText">Not entered</span>
                            </div>
                            <div class="strength-bar" id="strengthBar"></div>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-lock"></i>
                            <input type="password" 
                                   class="form-control" 
                                   id="confirm_password" 
                                   name="confirm_password" 
                                   placeholder="Confirm New Password"
                                   required>
                        </div>
                        
                        <!-- Password Requirements -->
                        <div class="requirements-list">
                            <strong>Password must contain:</strong>
                            <ul id="requirements">
                                <li id="req-length">
                                    <i class="fas fa-circle"></i> At least 8 characters
                                </li>
                                <li id="req-uppercase">
                                    <i class="fas fa-circle"></i> One uppercase letter
                                </li>
                                <li id="req-lowercase">
                                    <i class="fas fa-circle"></i> One lowercase letter
                                </li>
                                <li id="req-number">
                                    <i class="fas fa-circle"></i> One number
                                </li>
                                <li id="req-special">
                                    <i class="fas fa-circle"></i> One special character (@$!%*?&)
                                </li>
                            </ul>
                        </div>
                        
                        <button type="submit" class="btn-reset" id="resetBtn">
                            <span class="normal-state">
                                <i class="fas fa-sync-alt mr-2"></i> Reset Password
                            </span>
                            <span class="loading-state d-none">
                                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                Resetting...
                            </span>
                        </button>
                        
                        <a href="<?php echo base_url('login.php'); ?>" class="btn-login">
                            <i class="fas fa-arrow-left mr-2"></i> Back to Login
                        </a>
                    </form>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="login-footer">
            <p>&copy; <?php echo date('Y'); ?> <?php echo APP_NAME; ?>. All rights reserved.</p>
            <div class="developer-credit">
                Developed by <a href="#" target="_blank"><?php echo APP_COMPANY; ?></a>
            </div>
        </div>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            <?php if ($token_valid && !$message): ?>
            const $form = $('#resetForm');
            const $resetBtn = $('#resetBtn');
            const $normalState = $resetBtn.find('.normal-state');
            const $loadingState = $resetBtn.find('.loading-state');
            const $password = $('#password');
            const $confirm = $('#confirm_password');
            const $strengthBar = $('#strengthBar');
            const $strengthText = $('#strengthText');
            
            let submitted = false;
            
            // Password strength checker
            function checkPasswordStrength(password) {
                let strength = 0;
                const requirements = {
                    length: password.length >= 8,
                    uppercase: /[A-Z]/.test(password),
                    lowercase: /[a-z]/.test(password),
                    number: /[0-9]/.test(password),
                    special: /[@$!%*?&]/.test(password)
                };
                
                // Update requirements list
                $('#req-length i').toggleClass('fa-circle fa-check-circle text-success', requirements.length);
                $('#req-uppercase i').toggleClass('fa-circle fa-check-circle text-success', requirements.uppercase);
                $('#req-lowercase i').toggleClass('fa-circle fa-check-circle text-success', requirements.lowercase);
                $('#req-number i').toggleClass('fa-circle fa-check-circle text-success', requirements.number);
                $('#req-special i').toggleClass('fa-circle fa-check-circle text-success', requirements.special);
                
                // Calculate strength
                if (requirements.length) strength++;
                if (requirements.uppercase) strength++;
                if (requirements.lowercase) strength++;
                if (requirements.number) strength++;
                if (requirements.special) strength++;
                
                // Update strength bar
                $strengthBar.removeClass('strength-weak strength-medium strength-strong strength-very-strong');
                
                if (password.length === 0) {
                    $strengthBar.css('width', '0');
                    $strengthText.text('Not entered');
                } else if (strength <= 2) {
                    $strengthBar.addClass('strength-weak');
                    $strengthText.text('Weak');
                } else if (strength === 3) {
                    $strengthBar.addClass('strength-medium');
                    $strengthText.text('Medium');
                } else if (strength === 4) {
                    $strengthBar.addClass('strength-strong');
                    $strengthText.text('Strong');
                } else {
                    $strengthBar.addClass('strength-very-strong');
                    $strengthText.text('Very Strong');
                }
                
                return strength;
            }
            
            // Password input handler
            $password.on('input', function() {
                checkPasswordStrength($(this).val());
            });
            
            // Confirm password validation
            function validateConfirm() {
                if ($confirm.val() && $password.val() !== $confirm.val()) {
                    $confirm.addClass('is-invalid');
                    if ($confirm.next('.invalid-feedback').length === 0) {
                        $confirm.after('<div class="invalid-feedback">Passwords do not match</div>');
                    }
                    return false;
                } else {
                    $confirm.removeClass('is-invalid');
                    $confirm.next('.invalid-feedback').remove();
                    return true;
                }
            }
            
            $password.add($confirm).on('input', validateConfirm);
            
            // Form submission
            $form.on('submit', function(e) {
                if (submitted) {
                    e.preventDefault();
                    return false;
                }
                
                const password = $password.val();
                const strength = checkPasswordStrength(password);
                
                if (strength < 3) {
                    e.preventDefault();
                    alert('Please choose a stronger password');
                    return false;
                }
                
                if (!validateConfirm()) {
                    e.preventDefault();
                    return false;
                }
                
                // Show loading state
                $resetBtn.prop('disabled', true);
                $normalState.addClass('d-none');
                $loadingState.removeClass('d-none');
                
                submitted = true;
                return true;
            });
            
            // Prevent double submission on page refresh
            if (window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }
            <?php endif; ?>
        });
    </script>
</body>
</html>