<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
$adminAuth->requireAuth('admin_login.php');

$error = '';
$success = '';

// Handle password change form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    // Debug logging
    error_log("Password change attempt - Admin ID: " . ($_SESSION['admin_id'] ?? 'Not set'));
    error_log("Current password provided: " . (empty($currentPassword) ? 'No' : 'Yes'));
    error_log("New password provided: " . (empty($newPassword) ? 'No' : 'Yes'));
    
    // Validate input
    if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
        $error = 'Please fill in all fields.';
    } elseif ($newPassword !== $confirmPassword) {
        $error = 'New passwords do not match.';
    } elseif (strlen($newPassword) < 8) {
        $error = 'New password must be at least 8 characters long.';
    } elseif (!preg_match('/[A-Z]/', $newPassword)) {
        $error = 'New password must contain at least one uppercase letter.';
    } elseif (!preg_match('/[a-z]/', $newPassword)) {
        $error = 'New password must contain at least one lowercase letter.';
    } elseif (!preg_match('/\d/', $newPassword)) {
        $error = 'New password must contain at least one number.';
    } elseif ($currentPassword === $newPassword) {
        $error = 'New password must be different from your current password.';
    } else {
        // Check if admin ID is set
        if (!isset($_SESSION['admin_id'])) {
            $error = 'Session expired. Please log in again.';
        } else {
            // Change password using AdminAuth class
            $result = $adminAuth->changePassword($_SESSION['admin_id'], $currentPassword, $newPassword);
            
            error_log("Password change result: " . print_r($result, true));
            
            if ($result['success']) {
                $success = 'Password changed successfully! For security reasons, you may need to log in again.';
                // Clear the form
                $currentPassword = $newPassword = $confirmPassword = '';
            } else {
                $error = $result['error'];
            }
        }
    }
}
?>

<!-- Change Password Content -->
<div class="space-y-6">
    <!-- Page Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Change Password</h1>
            <p class="text-gray-600 dark:text-gray-400">Update your admin account password</p>
        </div>
        <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-xl flex items-center justify-center">
            <i class="fas fa-key text-white text-xl"></i>
        </div>
    </div>

    <!-- Password Change Card -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
        <!-- Error Message -->
        <?php if (!empty($error)): ?>
        <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6 flex items-center">
            <i class="fas fa-exclamation-circle mr-3"></i>
            <span><?= htmlspecialchars($error) ?></span>
        </div>
        <?php endif; ?>

        <!-- Success Message -->
        <?php if (!empty($success)): ?>
        <div class="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg mb-6 flex items-center">
            <i class="fas fa-check-circle mr-3"></i>
            <span><?= htmlspecialchars($success) ?></span>
        </div>
        <?php endif; ?>

        <!-- Password Change Form -->
        <form method="POST" class="space-y-6">
            <div>
                <label for="current_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    <i class="fas fa-lock mr-2"></i>Current Password
                </label>
                <input 
                    type="password" 
                    id="current_password" 
                    name="current_password" 
                    required
                    autocomplete="current-password"
                    class="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    placeholder="Enter your current password"
                >
            </div>

            <div>
                <label for="new_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    <i class="fas fa-key mr-2"></i>New Password
                </label>
                <input 
                    type="password" 
                    id="new_password" 
                    name="new_password" 
                    required
                    autocomplete="new-password"
                    minlength="8"
                    class="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    placeholder="Enter your new password"
                >
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Password must be at least 8 characters long with uppercase, lowercase, and numbers</p>
            </div>

            <div>
                <label for="confirm_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    <i class="fas fa-check mr-2"></i>Confirm New Password
                </label>
                <input 
                    type="password" 
                    id="confirm_password" 
                    name="confirm_password" 
                    required
                    autocomplete="new-password"
                    minlength="8"
                    class="w-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    placeholder="Confirm your new password"
                >
            </div>

            <div class="flex space-x-3">
                <button 
                    type="submit" 
                    name="change_password"
                    class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-lg font-medium hover:bg-blue-700 transition-colors"
                >
                    <i class="fas fa-save mr-2"></i>Change Password
                </button>
            </div>
        </form>

        <!-- Security Notice -->
        <div class="mt-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
            <div class="flex items-start">
                <i class="fas fa-info-circle text-yellow-600 dark:text-yellow-400 mr-3 mt-1"></i>
                <div class="text-sm text-yellow-800 dark:text-yellow-200">
                    <p class="font-medium mb-1">Security Tips</p>
                    <ul class="list-disc list-inside space-y-1">
                        <li>Use a strong, unique password</li>
                        <li>Include uppercase, lowercase, numbers, and symbols</li>
                        <li>Don't reuse passwords from other accounts</li>
                        <li>Consider using a password manager</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const newPasswordInput = document.getElementById('new_password');
    const confirmPasswordInput = document.getElementById('confirm_password');
    
    // Password confirmation validation
    confirmPasswordInput.addEventListener('input', function() {
        if (this.value !== newPasswordInput.value) {
            this.setCustomValidity('Passwords do not match');
        } else {
            this.setCustomValidity('');
        }
    });
    
    newPasswordInput.addEventListener('input', function() {
        if (confirmPasswordInput.value && this.value !== confirmPasswordInput.value) {
            confirmPasswordInput.setCustomValidity('Passwords do not match');
        } else {
            confirmPasswordInput.setCustomValidity('');
        }
    });
});
</script>
