<?php
// /zaka/study/beneficiary_print.php
// صفحة طباعة قوائم المستفيدين حسب التصنيف مع تحديد فردي أو الكل.
declare(strict_types=1);

ini_set('display_errors', '1');
error_reporting(E_ALL);

require_once dirname(__DIR__) . '/admin/bootstrap.php';
require_once __DIR__ . '/includes/functions_ai.php';

requireLogin();

function hp(string $v): string { return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }

$pdo = db();
$type = trim((string)($_GET['type'] ?? ''));
$distributionId = (int)($_GET['distribution_id'] ?? 0);

$typeMap = [
    'poor_families' => 'الأسر الفقيرة',
    'orphans' => 'الأيتام',
    'sponsorships' => 'الكفالات',
    'family_salaries' => 'رواتب الأسر',
    'external_beneficiaries' => 'مستفيدون عامّون',
    'distributions' => 'التوزيعات',
];

$title = $typeMap[$type] ?? 'قائمة المستفيدين';
$rows = [];
$distributions = [];

if ($type === 'distributions') {
    $distributions = $pdo->query("SELECT id, title, distribution_date FROM distributions ORDER BY distribution_date DESC, id DESC LIMIT 100")->fetchAll();
    if ($distributionId <= 0 && $distributions) {
        $distributionId = (int)$distributions[0]['id'];
    }
    if ($distributionId > 0) {
        $stmt = $pdo->prepare("\n            SELECT b.full_name, b.id_number, b.phone\n            FROM distribution_items di\n            INNER JOIN beneficiaries b ON b.id = di.beneficiary_id\n            WHERE di.distribution_id = ?\n            ORDER BY b.full_name ASC\n        ");
        $stmt->execute([$distributionId]);
        $rows = $stmt->fetchAll();
        foreach ($distributions as $d) {
            if ((int)$d['id'] === $distributionId) {
                $title = 'كشف توزيع: ' . (string)$d['title'] . ' - ' . (string)$d['distribution_date'];
                break;
            }
        }
    }
} else {
    $stmt = $pdo->prepare("\n        SELECT b.full_name, b.id_number, b.phone\n        FROM beneficiaries b\n        INNER JOIN beneficiary_types t ON t.id = b.beneficiary_type_id\n        WHERE t.slug = ? AND b.status = 'active'\n        ORDER BY b.file_number ASC, b.full_name ASC\n    ");
    $stmt->execute([$type]);
    $rows = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title><?= hp($title) ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
*{box-sizing:border-box}body{margin:0;background:#eef2f7;color:#111827;font-family:Tahoma,Arial,sans-serif}.page{max-width:1120px;margin:24px auto;background:#fff;border:1px solid #d8dee9;border-radius:14px;padding:22px}.header{display:flex;align-items:center;justify-content:space-between;border-bottom:2px solid #111827;padding-bottom:14px;margin-bottom:14px}.brand{display:flex;align-items:center;gap:14px}.logo{width:72px;height:72px;border:2px solid #1d4ed8;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:900;color:#1d4ed8}.title h1{margin:0;font-size:24px}.title p{margin:4px 0 0;color:#475569}.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0;padding:12px;background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px}.btn{border:0;border-radius:9px;padding:10px 14px;font-weight:700;cursor:pointer}.primary{background:#2563eb;color:#fff}.light{background:#e5e7eb}.success{background:#059669;color:#fff}select{padding:10px;border:1px solid #cbd5e1;border-radius:9px}table{width:100%;border-collapse:collapse;margin-top:12px}th,td{border:1px solid #111827;padding:9px;text-align:center;font-size:15px}th{background:#f1f5f9;font-weight:800}.name{text-align:right}.signature{height:42px;min-width:150px}.check-col{width:48px}.count{font-weight:700;color:#1d4ed8}.muted{color:#64748b}.print-only{display:none}@media print{body{background:#fff}.page{margin:0;max-width:none;border:0;border-radius:0;padding:10mm}.toolbar,.check-col,.no-print{display:none!important}.print-only{display:block}th,td{font-size:13px;padding:7px}.signature{height:38px}.header{break-after:avoid}tr{break-inside:avoid}}
</style>
</head>
<body>
<div class="page">
    <div class="header">
        <div class="brand">
            <div class="logo">اللجنة</div>
            <div class="title">
                <h1>لجنة زكاة وصدقات مخيم حطين</h1>
                <p><?= hp($title) ?></p>
            </div>
        </div>
        <div class="muted">تاريخ الطباعة: <?= hp(date('Y-m-d')) ?><br>عدد السجلات: <span class="count" id="selectedCount"><?= count($rows) ?></span></div>
    </div>

    <div class="toolbar no-print">
        <?php if ($type === 'distributions'): ?>
            <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
                <input type="hidden" name="type" value="distributions">
                <select name="distribution_id" onchange="this.form.submit()">
                    <?php foreach ($distributions as $d): ?>
                        <option value="<?= (int)$d['id'] ?>" <?= (int)$d['id']===$distributionId?'selected':'' ?>><?= hp((string)$d['title'] . ' - ' . (string)$d['distribution_date']) ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        <?php endif; ?>
        <button class="btn light" onclick="selectAllRows(true)">تحديد الكل</button>
        <button class="btn light" onclick="selectAllRows(false)">إلغاء التحديد</button>
        <button class="btn success" onclick="printSelected()">طباعة المحدد</button>
        <button class="btn primary" onclick="printAll()">طباعة الكل</button>
    </div>

    <table id="printTable">
        <thead><tr><th class="check-col no-print">اختيار</th><th>#</th><th>الاسم الرباعي</th><th>رقم الهوية / الرقم الوطني</th><th>رقم الهاتف</th><th>التوقيع</th></tr></thead>
        <tbody>
        <?php foreach ($rows as $i => $r): ?>
            <tr>
                <td class="check-col no-print"><input type="checkbox" class="row-check" checked onchange="updateCount()"></td>
                <td class="seq"><?= $i + 1 ?></td>
                <td class="name"><?= hp((string)$r['full_name']) ?></td>
                <td><?= hp((string)($r['id_number'] ?? '')) ?></td>
                <td><?= hp((string)($r['phone'] ?? '')) ?></td>
                <td class="signature"></td>
            </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?><tr><td colspan="6" class="muted">لا توجد بيانات للطباعة.</td></tr><?php endif; ?>
        </tbody>
    </table>
</div>
<script>
function updateCount(){document.getElementById('selectedCount').textContent=document.querySelectorAll('.row-check:checked').length;}
function selectAllRows(v){document.querySelectorAll('.row-check').forEach(c=>c.checked=v);updateCount();}
function renumberVisible(){let n=1;document.querySelectorAll('#printTable tbody tr').forEach(tr=>{if(tr.style.display!=='none'){const s=tr.querySelector('.seq');if(s)s.textContent=n++;}})}
function printSelected(){document.querySelectorAll('#printTable tbody tr').forEach(tr=>{const c=tr.querySelector('.row-check');if(c&&!c.checked)tr.style.display='none';});renumberVisible();window.print();setTimeout(()=>{document.querySelectorAll('#printTable tbody tr').forEach(tr=>tr.style.display='');renumberVisible();},500);}
function printAll(){selectAllRows(true);renumberVisible();window.print();}
updateCount();
</script>
</body>
</html>
