<?php
/**
 * تقرير تحصيل أسبوعي (قابل للطباعة / PDF من المتصفح)
 */
use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('billing.view')) {
    http_response_code(403);
    echo 'غير مسموح';
    return;
}

$tenantId = Tenant::id();
$weekStart = date('Y-m-d', strtotime('monday this week'));
$weekEnd = date('Y-m-d');

$rows = [];
$sumPaid = 0.0;
$sumUnpaid = 0.0;
try {
    $stmt = $db->prepare(
        "SELECT DATE(order_date) AS d,
                SUM(CASE WHEN payment_status = 'paid' THEN COALESCE(net_amount,0) ELSE 0 END) AS paid_amt,
                SUM(CASE WHEN payment_status IN ('unpaid','partial') THEN COALESCE(net_amount,0) ELSE 0 END) AS due_amt,
                COUNT(*) AS cnt
         FROM lab_orders
         WHERE tenant_id = ? AND DATE(order_date) BETWEEN ? AND ?
         GROUP BY DATE(order_date)
         ORDER BY d"
    );
    $stmt->execute([$tenantId, $weekStart, $weekEnd]);
    $rows = $stmt->fetchAll();
    foreach ($rows as $r) {
        $sumPaid += (float)($r['paid_amt'] ?? 0);
        $sumUnpaid += (float)($r['due_amt'] ?? 0);
    }
} catch (Throwable $e) {
}

$labName = '';
try {
    $stmt = $db->prepare('SELECT name FROM tenants WHERE id = ?');
    $stmt->execute([$tenantId]);
    $labName = (string)($stmt->fetchColumn() ?: '');
} catch (Throwable $e) {
}
?>
<div class="page-header">
    <h1>📊 التحصيل الأسبوعي</h1>
    <div class="actions-bar">
        <button type="button" class="btn-secondary" onclick="window.print()">طباعة / PDF</button>
        <a href="index.php?page=reports" class="btn-secondary">التقارير</a>
    </div>
</div>

<div class="card section-card" style="max-width:900px;">
    <p style="color:var(--text-muted);margin:0 0 16px;">
        الفترة: <strong><?php echo htmlspecialchars($weekStart, ENT_QUOTES, 'UTF-8'); ?></strong>
        إلى <strong><?php echo htmlspecialchars($weekEnd, ENT_QUOTES, 'UTF-8'); ?></strong>
        <?php if ($labName !== ''): ?> — <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?><?php endif; ?>
    </p>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:20px;">
        <div class="stat-card"><div class="stat-label">مدفوع (أسبوعي)</div><div class="stat-value"><?php echo number_format($sumPaid, 2); ?></div></div>
        <div class="stat-card"><div class="stat-label">مستحق (تقريبي)</div><div class="stat-value"><?php echo number_format($sumUnpaid, 2); ?></div></div>
    </div>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>اليوم</th>
                    <th>طلبات</th>
                    <th>مدفوع</th>
                    <th>مستحق</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $r): ?>
                <tr>
                    <td><?php echo htmlspecialchars($r['d'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo (int)$r['cnt']; ?></td>
                    <td><?php echo number_format((float)($r['paid_amt'] ?? 0), 2); ?></td>
                    <td><?php echo number_format((float)($r['due_amt'] ?? 0), 2); ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($rows)): ?>
                <tr><td colspan="4" style="text-align:center;color:var(--text-muted);">لا بيانات في هذا الأسبوع</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style media="print">
    .top-bar, .sidebar, .actions-bar, button { display: none !important; }
    .layout .content { margin: 0 !important; }
</style>
