<?php
/**
 * File Path: /zaka/admin/print_beneficiaries.php
 * Printable beneficiary lists by beneficiary type.
 */

declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
requireLogin();

$pdo = getPDO();

$typeId = isset($_GET['type']) ? (int)$_GET['type'] : 0;
if ($typeId <= 0) {
    http_response_code(400);
    exit('نوع المستفيد غير صحيح.');
}

$stmt = $pdo->prepare('SELECT id, name_ar FROM beneficiary_types WHERE id = ? AND is_active = 1 LIMIT 1');
$stmt->execute([$typeId]);
$type = $stmt->fetch();
if (!$type) {
    http_response_code(404);
    exit('التصنيف غير موجود.');
}

$selectedIds = [];
if (!empty($_GET['beneficiary_ids']) && is_array($_GET['beneficiary_ids'])) {
    foreach ($_GET['beneficiary_ids'] as $id) {
        $id = (int)$id;
        if ($id > 0) {
            $selectedIds[] = $id;
        }
    }
    $selectedIds = array_values(array_unique($selectedIds));
}

$params = [$typeId];
$sql = 'SELECT id, file_number, full_name, id_number, phone
        FROM beneficiaries
        WHERE beneficiary_type_id = ? AND status = "active"';

if ($selectedIds) {
    $placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
    $sql .= " AND id IN ($placeholders)";
    $params = array_merge($params, $selectedIds);
}

$sql .= ' ORDER BY file_number ASC, full_name ASC, id ASC';
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$beneficiaries = $stmt->fetchAll();

$allStmt = $pdo->prepare('SELECT id, file_number, full_name, id_number, phone
                         FROM beneficiaries
                         WHERE beneficiary_type_id = ? AND status = "active"
                         ORDER BY file_number ASC, full_name ASC, id ASC');
$allStmt->execute([$typeId]);
$allBeneficiaries = $allStmt->fetchAll();

$orgName    = function_exists('getSetting') ? getSetting('org_name', APP_NAME) : APP_NAME;
$orgPhone   = function_exists('getSetting') ? getSetting('org_phone', '') : '';
$orgAddress = function_exists('getSetting') ? getSetting('org_address', '') : '';
$logoPath   = function_exists('getSetting') ? (string)getSetting('org_logo', '') : '';
$typeName   = (string)$type['name_ar'];
$printedAt  = date('Y-m-d H:i');

function pe(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>كشف المستفيدين - <?= pe($typeName) ?></title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0;
            background: #eef3f8;
            color: #111827;
            font-family: Tahoma, Arial, sans-serif;
            font-size: 14px;
        }
        .page {
            width: 210mm;
            min-height: 297mm;
            margin: 12px auto;
            background: #fff;
            padding: 14mm 12mm;
            box-shadow: 0 8px 24px rgba(15, 23, 42, .12);
        }
        .toolbar {
            width: 210mm;
            margin: 14px auto 0;
            background: #fff;
            border: 1px solid #dbe3ef;
            border-radius: 14px;
            padding: 12px;
            display: flex;
            gap: 8px;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
        }
        .btn {
            border: 0;
            border-radius: 10px;
            padding: 9px 14px;
            cursor: pointer;
            font-weight: 700;
            text-decoration: none;
            display: inline-block;
        }
        .btn-primary { background: #2563eb; color: #fff; }
        .btn-success { background: #059669; color: #fff; }
        .btn-light { background: #eef2ff; color: #1e3a8a; }
        .select-box {
            margin: 12px auto;
            width: 210mm;
            background: #fff;
            border: 1px solid #dbe3ef;
            border-radius: 14px;
            padding: 12px;
        }
        .select-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            max-height: 210px;
            overflow: auto;
            padding: 6px;
        }
        .select-item {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 8px;
            background: #f8fafc;
            font-size: 13px;
        }
        .header {
            display: grid;
            grid-template-columns: 90px 1fr 150px;
            align-items: center;
            border-bottom: 3px solid #1d4ed8;
            padding-bottom: 12px;
            margin-bottom: 14px;
            gap: 12px;
        }
        .logo {
            width: 78px;
            height: 78px;
            border: 2px solid #1d4ed8;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #1d4ed8;
            font-weight: 900;
            font-size: 15px;
            text-align: center;
            overflow: hidden;
        }
        .logo img { width: 100%; height: 100%; object-fit: contain; }
        .title { text-align: center; }
        .title h1 { margin: 0 0 5px; font-size: 23px; }
        .title h2 { margin: 0; font-size: 19px; color: #1d4ed8; }
        .meta { font-size: 12px; line-height: 1.9; color: #334155; }
        .summary {
            display: flex;
            justify-content: space-between;
            margin: 10px 0 12px;
            padding: 8px 10px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
        }
        table { width: 100%; border-collapse: collapse; }
        th, td {
            border: 1px solid #9ca3af;
            padding: 8px 6px;
            text-align: center;
            vertical-align: middle;
        }
        th { background: #eaf1ff; font-weight: 800; }
        td.name { text-align: right; font-weight: 700; }
        .col-no { width: 45px; }
        .col-id { width: 130px; }
        .col-phone { width: 115px; }
        .col-sign { width: 155px; height: 42px; }
        .footer {
            margin-top: 18px;
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 18px;
            font-weight: 700;
        }
        .sign-line { border-top: 1px solid #111827; padding-top: 8px; text-align: center; }
        .empty { text-align: center; padding: 30px; color: #64748b; border: 1px dashed #cbd5e1; }
        @media print {
            body { background: #fff; font-size: 12px; }
            .toolbar, .select-box { display: none !important; }
            .page { width: auto; min-height: auto; margin: 0; padding: 8mm; box-shadow: none; }
            @page { size: A4 portrait; margin: 8mm; }
            .header { break-inside: avoid; }
            tr { break-inside: avoid; page-break-inside: avoid; }
        }
    </style>
</head>
<body>

<div class="toolbar">
    <div>
        <strong>كشف <?= pe($typeName) ?></strong>
        <span style="color:#64748b">- المعروض: <?= count($beneficiaries) ?> من <?= count($allBeneficiaries) ?></span>
    </div>
    <div>
        <a class="btn btn-light" href="<?= pe(ADMIN_PATH) ?>/dashboard.php">العودة للوحة التحكم</a>
        <a class="btn btn-success" href="<?= pe(ADMIN_PATH) ?>/print_beneficiaries.php?type=<?= (int)$typeId ?>">عرض الكل</a>
        <button class="btn btn-primary" onclick="window.print()">طباعة</button>
    </div>
</div>

<div class="select-box">
    <form method="get" action="print_beneficiaries.php">
        <input type="hidden" name="type" value="<?= (int)$typeId ?>">
        <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:8px;">
            <strong>تحديد فردي للطباعة</strong>
            <div>
                <button type="button" class="btn btn-light" onclick="toggleAll(true)">تحديد الكل</button>
                <button type="button" class="btn btn-light" onclick="toggleAll(false)">إلغاء التحديد</button>
                <button type="submit" class="btn btn-primary">عرض المحدد</button>
            </div>
        </div>
        <div class="select-grid">
            <?php foreach ($allBeneficiaries as $b): ?>
                <?php $checked = !$selectedIds || in_array((int)$b['id'], $selectedIds, true); ?>
                <label class="select-item">
                    <input type="checkbox" name="beneficiary_ids[]" value="<?= (int)$b['id'] ?>" <?= $checked ? 'checked' : '' ?>>
                    <?= pe((string)$b['full_name']) ?>
                </label>
            <?php endforeach; ?>
        </div>
    </form>
</div>

<div class="page">
    <div class="header">
        <div class="logo">
            <?php if ($logoPath !== ''): ?>
                <img src="<?= pe($logoPath) ?>" alt="شعار اللجنة">
            <?php else: ?>
                شعار<br>اللجنة
            <?php endif; ?>
        </div>
        <div class="title">
            <h1><?= pe((string)$orgName) ?></h1>
            <h2>كشف المستفيدين - <?= pe($typeName) ?></h2>
        </div>
        <div class="meta">
            <div><strong>تاريخ الطباعة:</strong> <?= pe($printedAt) ?></div>
            <?php if ($orgPhone !== ''): ?><div><strong>الهاتف:</strong> <?= pe((string)$orgPhone) ?></div><?php endif; ?>
            <?php if ($orgAddress !== ''): ?><div><strong>العنوان:</strong> <?= pe((string)$orgAddress) ?></div><?php endif; ?>
        </div>
    </div>

    <div class="summary">
        <div><strong>التصنيف:</strong> <?= pe($typeName) ?></div>
        <div><strong>عدد الأسماء:</strong> <?= count($beneficiaries) ?></div>
        <div><strong>نوع الكشف:</strong> <?= $selectedIds ? 'محدد' : 'كامل' ?></div>
    </div>

    <?php if ($beneficiaries): ?>
        <table>
            <thead>
            <tr>
                <th class="col-no">م</th>
                <th>الاسم الرباعي</th>
                <th class="col-id">الرقم الوطني</th>
                <th class="col-phone">رقم الهاتف</th>
                <th class="col-sign">التوقيع</th>
            </tr>
            </thead>
            <tbody>
            <?php foreach ($beneficiaries as $index => $b): ?>
                <tr>
                    <td><?= $index + 1 ?></td>
                    <td class="name"><?= pe((string)$b['full_name']) ?></td>
                    <td><?= pe((string)($b['id_number'] ?? '')) ?></td>
                    <td><?= pe((string)($b['phone'] ?? '')) ?></td>
                    <td></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="footer">
            <div class="sign-line">مسؤول الكشف</div>
            <div class="sign-line">المحاسب / المدقق</div>
            <div class="sign-line">رئيس اللجنة</div>
        </div>
    <?php else: ?>
        <div class="empty">لا يوجد مستفيدون نشطون ضمن هذا التصنيف.</div>
    <?php endif; ?>
</div>

<script>
function toggleAll(state) {
    document.querySelectorAll('input[name="beneficiary_ids[]"]').forEach(function (el) {
        el.checked = state;
    });
}
</script>

</body>
</html>
