<?php
/**
 * Prince VIP System - Agents Management (Admin Only)
 * إدارة الوكلاء
 */
$pageTitle = 'إدارة الوكلاء';
require_once 'includes/header.php';

if (!isAdmin()) { redirect('dashboard.php'); }

$db = getDB();
$agents = $db->query("SELECT u.*, 
    (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id) as total_contracts,
    (SELECT COUNT(*) FROM contracts WHERE agent_id = u.id AND status = 'active') as active_contracts
    FROM users u WHERE u.role = 'agent' ORDER BY u.created_at DESC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1"><i class="fas fa-user-tie text-primary me-2"></i>إدارة الوكلاء</h4>
        <p class="text-muted small mb-0">إضافة وتعديل وتعطيل الوكلاء</p>
    </div>
    <button class="btn btn-gold" data-bs-toggle="modal" data-bs-target="#addAgentModal">
        <i class="fas fa-plus me-1"></i> وكيل جديد
    </button>
</div>

<div class="content-card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>الاسم</th>
                        <th>اسم المستخدم</th>
                        <th>البريد الإلكتروني</th>
                        <th>الجوال</th>
                        <th>العقود</th>
                        <th>الحالة</th>
                        <th>آخر دخول</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($agents as $i => $agent): ?>
                    <tr>
                        <td><?= $i + 1 ?></td>
                        <td class="fw-bold"><?= clean($agent['full_name']) ?></td>
                        <td><?= clean($agent['username']) ?></td>
                        <td><?= clean($agent['email'] ?? '-') ?></td>
                        <td><?= clean($agent['phone'] ?? '-') ?></td>
                        <td>
                            <span class="badge bg-primary"><?= $agent['total_contracts'] ?></span>
                            <span class="badge bg-success"><?= $agent['active_contracts'] ?> نشط</span>
                        </td>
                        <td>
                            <?php if ($agent['is_active']): ?>
                            <span class="status-badge active">فعال</span>
                            <?php else: ?>
                            <span class="status-badge draft">معطل</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-muted small"><?= $agent['last_login'] ? date('Y/m/d H:i', strtotime($agent['last_login'])) : 'لم يسجل' ?></td>
                        <td>
                            <button class="btn btn-sm btn-outline-gold me-1" onclick="editAgent(<?= htmlspecialchars(json_encode($agent)) ?>)">
                                <i class="fas fa-edit"></i>
                            </button>
                            <?php if ($agent['is_active']): ?>
                            <button class="btn btn-sm btn-outline-danger" onclick="toggleAgent(<?= $agent['id'] ?>, 0)">
                                <i class="fas fa-ban"></i>
                            </button>
                            <?php else: ?>
                            <button class="btn btn-sm btn-outline-success" onclick="toggleAgent(<?= $agent['id'] ?>, 1)">
                                <i class="fas fa-check"></i>
                            </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($agents)): ?>
                    <tr><td colspan="9" class="text-center text-muted py-4">لا يوجد وكلاء مسجلين</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- مودال إضافة وكيل -->
<div class="modal fade" id="addAgentModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-user-plus text-primary me-2"></i>إضافة وكيل جديد</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addAgentForm">
                    <div class="form-group">
                        <label>الاسم الكامل <span class="required">*</span></label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>اسم المستخدم <span class="required">*</span></label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>كلمة المرور <span class="required">*</span></label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>البريد الإلكتروني</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                    <div class="form-group mb-0">
                        <label>رقم الجوال</label>
                        <input type="text" name="phone" class="form-control">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" id="saveAgent" class="btn btn-gold">إضافة الوكيل</button>
            </div>
        </div>
    </div>
</div>

<!-- مودال تعديل -->
<div class="modal fade" id="editAgentModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-edit text-primary me-2"></i>تعديل بيانات الوكيل</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editAgentForm">
                    <input type="hidden" name="agent_id" id="eAgentId">
                    <div class="form-group">
                        <label>الاسم الكامل</label>
                        <input type="text" name="full_name" id="eFullName" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>البريد الإلكتروني</label>
                        <input type="email" name="email" id="eEmail" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>رقم الجوال</label>
                        <input type="text" name="phone" id="ePhone" class="form-control">
                    </div>
                    <div class="form-group mb-0">
                        <label>كلمة مرور جديدة <small class="text-muted">(اتركه فارغاً للإبقاء على الحالية)</small></label>
                        <input type="password" name="new_password" class="form-control">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" id="updateAgent" class="btn btn-gold">تحديث</button>
            </div>
        </div>
    </div>
</div>

<?php
$extraJS = <<<'JS'
<script>
$('#saveAgent').on('click', function() {
    ajaxRequest('ajax/agents.php', $('#addAgentForm').serialize() + '&action=create', function(r) {
        if (r.success) { showAlert(r.message, 'success'); setTimeout(() => location.reload(), 1000); }
        else showAlert(r.message, 'danger');
    });
});

$('#updateAgent').on('click', function() {
    ajaxRequest('ajax/agents.php', $('#editAgentForm').serialize() + '&action=update', function(r) {
        if (r.success) { showAlert(r.message, 'success'); setTimeout(() => location.reload(), 1000); }
        else showAlert(r.message, 'danger');
    });
});

function editAgent(a) {
    $('#eAgentId').val(a.id);
    $('#eFullName').val(a.full_name);
    $('#eEmail').val(a.email);
    $('#ePhone').val(a.phone);
    new bootstrap.Modal('#editAgentModal').show();
}

function toggleAgent(id, status) {
    const msg = status ? 'تفعيل هذا الوكيل؟' : 'تعطيل هذا الوكيل؟';
    confirmAction(msg, function() {
        ajaxRequest('ajax/agents.php', {action:'toggle', agent_id: id, is_active: status}, function(r) {
            if (r.success) { showAlert(r.message, 'success'); setTimeout(() => location.reload(), 1000); }
            else showAlert(r.message, 'danger');
        });
    });
}
</script>
JS;

require_once 'includes/footer.php';
?>
