<?php
/**
 * Prince VIP System - Reports (Admin Only)
 */
$pageTitle = 'التقارير';
require_once 'includes/header.php';
if (!isAdmin()) { redirect('dashboard.php'); }
$db = getDB();

// إحصائيات عامة
$totalContracts = $db->query("SELECT COUNT(*) FROM contracts")->fetchColumn();
$activeContracts = $db->query("SELECT COUNT(*) FROM contracts WHERE status = 'active'")->fetchColumn();
$totalClients = $db->query("SELECT COUNT(*) FROM clients")->fetchColumn();
$totalAgents = $db->query("SELECT COUNT(*) FROM users WHERE role = 'agent'")->fetchColumn();

// توزيع العقود حسب الحالة
$statusDist = $db->query("SELECT status, COUNT(*) as cnt FROM contracts GROUP BY status")->fetchAll();

// توزيع العقود حسب الوكيل
$agentDist = $db->query("SELECT u.full_name, COUNT(c.id) as cnt FROM users u LEFT JOIN contracts c ON c.agent_id = u.id WHERE u.role = 'agent' GROUP BY u.id ORDER BY cnt DESC")->fetchAll();

// العقود حسب الشهر (آخر 12 شهر)
$monthlyContracts = $db->query("SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as cnt FROM contracts WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH) GROUP BY month ORDER BY month")->fetchAll();

// توزيع حسب نوع التأمين
$insuranceDist = $db->query("SELECT insurance_type, COUNT(*) as cnt FROM contracts WHERE insurance_type IS NOT NULL AND insurance_type != '' GROUP BY insurance_type ORDER BY cnt DESC")->fetchAll();

$statusLabels = ['draft' => 'مسودة', 'pending' => 'قيد المراجعة', 'active' => 'نشط', 'rejected' => 'مرفوض', 'expired' => 'منتهي'];
?>

<h4 class="fw-bold mb-4"><i class="fas fa-chart-bar text-primary me-2"></i>التقارير والإحصائيات</h4>

<!-- إحصائيات سريعة -->
<div class="stat-cards">
    <div class="stat-card">
        <div class="stat-icon">📋</div>
        <div class="stat-label">إجمالي العقود</div>
        <div class="stat-value"><?= $totalContracts ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">✅</div>
        <div class="stat-label">عقود نشطة</div>
        <div class="stat-value"><?= $activeContracts ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">👥</div>
        <div class="stat-label">العملاء</div>
        <div class="stat-value"><?= $totalClients ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon">🧑‍💼</div>
        <div class="stat-label">الوكلاء</div>
        <div class="stat-value"><?= $totalAgents ?></div>
    </div>
</div>

<div class="row">
    <!-- توزيع حسب الحالة -->
    <div class="col-lg-6 mb-4">
        <div class="content-card">
            <div class="card-header">
                <h5><i class="fas fa-chart-pie text-primary"></i> توزيع العقود حسب الحالة</h5>
            </div>
            <div class="card-body">
                <?php foreach ($statusDist as $st): ?>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="d-flex align-items-center gap-2">
                        <span class="status-badge <?= $st['status'] ?>"><?= $statusLabels[$st['status']] ?? $st['status'] ?></span>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <div class="progress" style="width:150px;height:8px;">
                            <div class="progress-bar bg-primary" style="width:<?= $totalContracts > 0 ? round(($st['cnt']/$totalContracts)*100) : 0 ?>%"></div>
                        </div>
                        <strong><?= $st['cnt'] ?></strong>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <!-- توزيع حسب الوكيل -->
    <div class="col-lg-6 mb-4">
        <div class="content-card">
            <div class="card-header">
                <h5><i class="fas fa-users text-success"></i> العقود حسب الوكيل</h5>
            </div>
            <div class="card-body">
                <?php foreach ($agentDist as $ag): ?>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span class="fw-bold"><?= clean($ag['full_name']) ?></span>
                    <div class="d-flex align-items-center gap-2">
                        <div class="progress" style="width:150px;height:8px;">
                            <div class="progress-bar bg-success" style="width:<?= $totalContracts > 0 ? round(($ag['cnt']/$totalContracts)*100) : 0 ?>%"></div>
                        </div>
                        <strong><?= $ag['cnt'] ?></strong>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <!-- العقود الشهرية -->
    <div class="col-lg-6 mb-4">
        <div class="content-card">
            <div class="card-header">
                <h5><i class="fas fa-calendar-alt text-info"></i> العقود حسب الشهر</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead><tr><th>الشهر</th><th>عدد العقود</th></tr></thead>
                        <tbody>
                            <?php foreach ($monthlyContracts as $mc): ?>
                            <tr><td><?= $mc['month'] ?></td><td><strong><?= $mc['cnt'] ?></strong></td></tr>
                            <?php endforeach; ?>
                            <?php if (empty($monthlyContracts)): ?>
                            <tr><td colspan="2" class="text-center text-muted py-3">لا توجد بيانات</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- توزيع حسب نوع التأمين -->
    <div class="col-lg-6 mb-4">
        <div class="content-card">
            <div class="card-header">
                <h5><i class="fas fa-shield-alt text-warning"></i> توزيع حسب نوع التأمين</h5>
            </div>
            <div class="card-body">
                <?php foreach ($insuranceDist as $ins): ?>
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <span><?= clean($ins['insurance_type']) ?></span>
                    <div class="d-flex align-items-center gap-2">
                        <div class="progress" style="width:150px;height:8px;">
                            <div class="progress-bar bg-warning" style="width:<?= $totalContracts > 0 ? round(($ins['cnt']/$totalContracts)*100) : 0 ?>%"></div>
                        </div>
                        <strong><?= $ins['cnt'] ?></strong>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($insuranceDist)): ?>
                <div class="text-center text-muted py-3">لا توجد بيانات</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- سجل النشاطات -->
<div class="content-card">
    <div class="card-header">
        <h5><i class="fas fa-history text-secondary"></i> آخر النشاطات</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr><th>المستخدم</th><th>الإجراء</th><th>الوصف</th><th>التاريخ</th></tr>
                </thead>
                <tbody>
                    <?php
                    $activities = $db->query("SELECT al.*, u.full_name FROM activity_log al LEFT JOIN users u ON al.user_id = u.id ORDER BY al.created_at DESC LIMIT 20")->fetchAll();
                    foreach ($activities as $act):
                    ?>
                    <tr>
                        <td class="fw-bold"><?= clean($act['full_name'] ?? 'غير معروف') ?></td>
                        <td><?= clean($act['action']) ?></td>
                        <td class="text-muted"><?= clean($act['description']) ?></td>
                        <td class="text-muted small"><?= date('Y/m/d H:i', strtotime($act['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($activities)): ?>
                    <tr><td colspan="4" class="text-center text-muted py-3">لا توجد نشاطات</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
