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

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Get agents list
$sql = "SELECT * FROM agent ORDER BY agent_name";
$result = $conn->query($sql);
$agents = $result->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agents Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Agents Management')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Agents</h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_agent.php" class="btn btn-success btn-sm">
                                            <i class="ri-add-line align-bottom"></i> Add New Agent
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="agents-table" class="table table-bordered nowrap table-striped align-middle">
                                            <thead>
                                                <tr>
                                                    <th>Agent ID</th>
                                                    <th>Agent Name</th>
                                                    <th>Agent Type</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($agents as $agent): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($agent['agent_id']); ?></td>
                                                    <td><?php echo htmlspecialchars($agent['agent_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($agent['agent_type']); ?></td>
                                                    <td>
                                                        <div class="dropdown d-inline-block">
                                                            <button class="btn btn-soft-secondary btn-sm dropdown" 
                                                                    type="button" data-bs-toggle="dropdown" 
                                                                    aria-expanded="false">
                                                                <i class="ri-more-fill align-middle"></i>
                                                            </button>
                                                            <ul class="dropdown-menu dropdown-menu-end">
                                                                <li>
                                                                    <a href="edit_agent.php?id=<?php echo $agent['agent_id']; ?>" 
                                                                       class="dropdown-item">
                                                                        <i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a href="javascript:void(0);" 
                                                                       class="dropdown-item text-danger"
                                                                       onclick="deleteAgent(<?php echo $agent['agent_id']; ?>)">
                                                                        <i class="ri-delete-bin-line align-bottom me-2 text-danger"></i>
                                                                        Delete
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/app.js"></script>
    <script>
        $(document).ready(function() {
            $('#agents-table').DataTable({
                responsive: true,
                lengthMenu: [10, 25, 50, 75, 100],
                language: {
                    search: "Search agents:",
                    lengthMenu: "Show _MENU_ agents"
                }
            });
        });

        function deleteAgent(agentId) {
            Swal.fire({
                title: 'Delete Agent?',
                text: 'Are you sure you want to delete this agent?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('delete_agent.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ agent_id: agentId })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire('Success', 'Agent deleted successfully', 'success').then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('Error', 'An error occurred while deleting the agent', 'error');
                    });
                }
            });
        }
    </script>
</body>
</html> 