<?php
require_once './includes/session.php';
require_once './includes/admin.php';
require_once './includes/utils.php';

// Initialize session and required classes
$session = SessionManager::getInstance();
$adminObj = new Admin();

// Get admin details
$adminId = $session->getUserId();
$admin = $adminObj->getAdminById($adminId);

$successMessage = '';
$errorMessage = '';

// Process password change form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_password') {
    // Check for CSRF token
    if (!isset($_POST['csrf_token']) || !Utils::validateCSRFToken($_POST['csrf_token'])) {
        $errorMessage = 'Invalid request. Please try again.';
    } else {
        // Get form data
        $currentPassword = isset($_POST['current_password']) ? $_POST['current_password'] : '';
        $newPassword = isset($_POST['new_password']) ? $_POST['new_password'] : '';
        $confirmPassword = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';

        // Validate input
        if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
            $errorMessage = 'All password fields are required.';
        } elseif ($newPassword !== $confirmPassword) {
            $errorMessage = 'New password and confirm password do not match.';
        } elseif (strlen($newPassword) < 6) {
            $errorMessage = 'New password must be at least 6 characters long.';
        } else {
            // Update password
            if ($adminObj->changePassword($adminId, $currentPassword, $newPassword)) {
                Utils::logActivity($adminId, 'change_password', 'Admin changed password');
                $successMessage = 'Password updated successfully.';
            } else {
                $errorMessage = 'Current password is incorrect.';
            }
        }
    }
}

// Process verification password change form
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_verifypass') {
    // Check for CSRF token
    if (!isset($_POST['csrf_token']) || !Utils::validateCSRFToken($_POST['csrf_token'])) {
        $errorMessage = 'Invalid request. Please try again.';
    } else {
        // Get form data
        $verifyPass = isset($_POST['verifypass']) ? Utils::sanitizeInput($_POST['verifypass']) : '';

        // Validate input
        if (empty($verifyPass)) {
            $errorMessage = 'Verification password cannot be empty.';
        } else {
            // Update verification password
            if ($adminObj->updateVerificationPassword($adminId, $verifyPass)) {
                Utils::logActivity($adminId, 'change_verifypass', 'Admin changed verification password');
                $successMessage = 'Verification password updated successfully.';

                // Refresh admin data
                $admin = $adminObj->getAdminById($adminId);
            } else {
                $errorMessage = 'Failed to update verification password.';
            }
        }
    }
}

// Generate CSRF token
$csrfToken = Utils::generateCSRFToken();

// Include header
include_once './includes/header.php';
?>

<!-- Page Content -->

<!-- Alert Messages -->
<?php if (!empty($successMessage)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo htmlspecialchars($successMessage); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if (!empty($errorMessage)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo htmlspecialchars($errorMessage); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row">
    <!-- Admin Info -->
    <div class="col-md-4 mb-4">
        <div class="card">
            <div class="card-header">
                <span>Admin Information</span>
            </div>
            <div class="card-body">
                <div class="text-center mb-4">
                    <div class="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center mx-auto" style="width: 80px; height: 80px; font-size: 32px;">
                        <?php echo strtoupper(substr($admin['email'], 0, 1)); ?>
                    </div>
                    <h5 class="mt-3"><?php echo htmlspecialchars($admin['email']); ?></h5>
                </div>

                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Admin ID</span>
                        <span class="text-muted"><?php echo htmlspecialchars($admin['id']); ?></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Created Date</span>
                        <span class="text-muted"><?php echo Utils::formatDate($admin['date'], 'd M Y H:i'); ?></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Last Login</span>
                        <span class="text-muted"><?php echo date('d M Y H:i'); ?></span>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Change Password -->
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <span>Change Password</span>
            </div>
            <div class="card-body">
                <form id="password-form" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="change_password">

                    <div class="mb-3">
                        <label for="current_password" class="form-label">Current Password</label>
                        <input type="password" class="form-control" id="current_password" name="current_password" required>
                    </div>

                    <div class="mb-3">
                        <label for="new_password" class="form-label">New Password</label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required>
                        <div class="form-text">Password must be at least 6 characters long.</div>
                    </div>

                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirm New Password</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">Change Password</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Change Verification Password -->
        <div class="card">
            <div class="card-header">
                <span>Change Verification Password</span>
            </div>
            <div class="card-body">
                <form id="verifypass-form" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="action" value="change_verifypass">

                    <div class="mb-3">
                        <label for="verifypass" class="form-label">Verification Password</label>
                        <input type="text" class="form-control" id="verifypass" name="verifypass" value="<?php echo htmlspecialchars($admin['verifypass'] ?? ''); ?>" required>
                        <div class="form-text">This password is used for additional verification.</div>
                    </div>

                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">Update Verification Password</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
// Include footer
include_once './includes/footer.php';
?>
