<?php
$page_title = 'My Profile - Admin';

if (!Admin::isLoggedIn()) {
    Utils::redirect('/routex/admin/login');
}

require_once __DIR__ . '/../../includes/trackheader.php';

$admin_model = new Admin($pdo);
$current_admin = $admin_model->getCurrentAdmin();
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!Utils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token.';
    } else {
        $full_name = trim($_POST['full_name'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if (empty($full_name)) {
            $error = 'Full name is required.';
        } elseif (!empty($password)) {
            if (strlen($password) < 6) {
                $error = 'Password must be at least 6 characters.';
            } elseif ($password !== $confirm_password) {
                $error = 'Passwords do not match.';
            }
        }

        if (empty($error)) {
            try {
                // Update query
                $sql = "UPDATE admins SET full_name = :full_name";
                $params = [':full_name' => $full_name, ':id' => $_SESSION['admin_id']];

                if (!empty($password)) {
                    $sql .= ", password = :password";
                    $params[':password'] = password_hash($password, PASSWORD_BCRYPT);
                }

                $sql .= " WHERE id = :id";
                $stmt = $pdo->prepare($sql);
                
                if ($stmt->execute($params)) {
                    $success = 'Profile updated successfully.';
                    // Refresh admin data
                    $current_admin = $admin_model->getCurrentAdmin();
                } else {
                    $error = 'Failed to update profile.';
                }
            } catch (PDOException $e) {
                $error = 'Database error: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = Utils::generateCSRFToken();
?>

<section class="min-h-screen bg-gray-50">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <!-- Header -->
        <div class="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
            <div>
                <h1 class="text-4xl font-bold text-gray-900">My Profile</h1>
                <p class="text-gray-600 mt-2">Manage your account details</p>
            </div>
            <a href="/routex/admin/dashboard" class="px-6 py-3 bg-white text-gray-700 border-2 border-gray-300 rounded-lg font-semibold hover:bg-gray-50 transition-all duration-300">
                <i class="fas fa-arrow-left mr-2"></i>Dashboard
            </a>
        </div>

        <!-- Form -->
        <div class="bg-white rounded-xl shadow-md p-8">
            <?php if ($error): ?>
            <div class="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg mb-6">
                <p class="text-red-700"><?php echo htmlspecialchars($error); ?></p>
            </div>
            <?php endif; ?>

            <?php if ($success): ?>
            <div class="bg-green-50 border-l-4 border-green-500 p-4 rounded-lg mb-6">
                <p class="text-green-700"><?php echo htmlspecialchars($success); ?></p>
            </div>
            <?php endif; ?>

            <form method="POST" class="space-y-6">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Username</label>
                    <input type="text" value="<?php echo htmlspecialchars($current_admin['username']); ?>" class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg bg-gray-100 text-gray-500 cursor-not-allowed" readonly>
                    <p class="text-sm text-gray-500 mt-1">Username cannot be changed.</p>
                </div>

                <div>
                    <label class="block text-gray-900 font-semibold mb-2">Full Name</label>
                    <input type="text" name="full_name" value="<?php echo htmlspecialchars($current_admin['full_name']); ?>" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600" required>
                </div>

                <div class="border-t pt-6 mt-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4">Change Password</h3>
                    <p class="text-gray-600 text-sm mb-4">Leave blank if you don't want to change your password.</p>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-900 font-semibold mb-2">New Password</label>
                            <div class="relative">
                                <input type="password" name="password" id="new_password" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 pr-10">
                                <button type="button" onclick="togglePassword('new_password', 'toggleIconNew')" class="absolute inset-y-0 right-0 px-3 flex items-center text-gray-500 hover:text-gray-700 focus:outline-none">
                                    <i id="toggleIconNew" class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        <div>
                            <label class="block text-gray-900 font-semibold mb-2">Confirm Password</label>
                            <div class="relative">
                                <input type="password" name="confirm_password" id="confirm_password" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:outline-none focus:border-purple-600 pr-10">
                                <button type="button" onclick="togglePassword('confirm_password', 'toggleIconConfirm')" class="absolute inset-y-0 right-0 px-3 flex items-center text-gray-500 hover:text-gray-700 focus:outline-none">
                                    <i id="toggleIconConfirm" class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="pt-4">
                    <button type="submit" class="btn-primary">
                        <i class="fas fa-save mr-2"></i>Update Profile
                    </button>
                </div>
            </form>
        </div>
    </div>
</section>

<script>
function togglePassword(inputId, iconId) {
    const input = document.getElementById(inputId);
    const icon = document.getElementById(iconId);
    if (input.type === "password") {
        input.type = "text";
        icon.classList.remove("fa-eye");
        icon.classList.add("fa-eye-slash");
    } else {
        input.type = "password";
        icon.classList.remove("fa-eye-slash");
        icon.classList.add("fa-eye");
    }
}
</script>

<footer class="bg-white border-t mt-20 no-print">
  <div class="max-w-7xl mx-auto px-4 py-6 text-center text-sm text-slate-500">
    © 2026 RoutexShipping. All rights reserved.
  </div>
</footer>