<?php
/**
 * لوحة مركزية: مقارنة أداء الفروع (للإدارة العليا)
 */
use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('branches.manage')) {
    http_response_code(403);
    echo 'هذه الصفحة للمديرين فقط.';
    return;
}

$tenantId = Tenant::id();
$tenantCond = '';
try {
    $db->query('SELECT tenant_id FROM branches LIMIT 1');
    $tenantCond = ' AND b.tenant_id = ' . (int)$tenantId;
} catch (Throwable $e) {}

$branchStats = [];
try {
    $stmt = $db->query(
        "SELECT b.id, b.name, b.branch_code,
                (SELECT COUNT(*) FROM lab_orders o WHERE o.branch_id = b.id) AS orders_count,
                (SELECT COUNT(*) FROM lab_orders o WHERE o.branch_id = b.id AND DATE(o.order_date) = CURDATE()) AS today_orders,
                (SELECT COALESCE(SUM(o.net_amount), 0) FROM lab_orders o WHERE o.branch_id = b.id AND o.payment_status = 'paid') AS total_paid,
                (SELECT COUNT(DISTINCT o.patient_id) FROM lab_orders o WHERE o.branch_id = b.id) AS unique_patients
         FROM branches b
         WHERE b.is_active = 1 $tenantCond
         ORDER BY orders_count DESC"
    );
    $branchStats = $stmt->fetchAll();
} catch (Throwable $e) {
}
$totals = ['orders' => 0, 'today' => 0, 'paid' => 0];
foreach ($branchStats as $b) {
    $totals['orders'] += (int)$b['orders_count'];
    $totals['today'] += (int)$b['today_orders'];
    $totals['paid'] += (float)$b['total_paid'];
}
?>
<div class="page-header">
    <h1>لوحة مركزية - أداء الفروع</h1>
    <a href="index.php?page=branches" class="btn-secondary">إدارة الفروع</a>
</div>
<div class="stats-grid" style="margin-bottom:24px;">
    <div class="stat-card">
        <div class="stat-label">إجمالي الطلبات</div>
        <div class="stat-value"><?php echo $totals['orders']; ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">طلبات اليوم</div>
        <div class="stat-value"><?php echo $totals['today']; ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">إجمالي الإيرادات (مدفوعة)</div>
        <div class="stat-value"><?php echo number_format($totals['paid'], 2); ?></div>
    </div>
</div>
<div class="section-card">
    <h3>مقارنة الفروع</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>الفرع</th>
                    <th>الكود</th>
                    <th>الطلبات</th>
                    <th>اليوم</th>
                    <th>المدفوع</th>
                    <th>مرضى مميزين</th>
                    <th>إجراء</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($branchStats as $b): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($b['name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td><?php echo htmlspecialchars($b['branch_code'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo (int)$b['orders_count']; ?></td>
                    <td><?php echo (int)$b['today_orders']; ?></td>
                    <td><?php echo number_format((float)$b['total_paid'], 2); ?></td>
                    <td><?php echo (int)$b['unique_patients']; ?></td>
                    <td>
                        <a href="index.php?page=orders&branch_id=<?php echo (int)$b['id']; ?>">طلبات</a>
                        <a href="index.php?page=reports&branch_id=<?php echo (int)$b['id']; ?>">تقارير</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
