<?php
// /zaka/study/response_print.php
declare(strict_types=1);

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'); }

$view = trim((string)($_GET['view'] ?? 'all'));
$allowedViews = ['all','approved','rejected','reserve','waiting','suspicious'];
if (!in_array($view, $allowedViews, true)) $view = 'all';

$export = trim((string)($_GET['export'] ?? ''));

function responsePrintMatchesView(array $row, string $view): bool
{
    $com = (string)($row['committee_status'] ?? 'pending');
    $sus = (int)($row['suspicion_score'] ?? 0);
    return match ($view) {
        'approved'   => $com === 'approved',
        'rejected'   => $com === 'rejected',
        'reserve'    => $com === 'reserve',
        'waiting'    => in_array($com, ['pending','review','waiting'], true),
        'suspicious' => $sus >= 35,
        default      => true,
    };
}

$viewTitles = [
    'all'        => 'كشف جميع الردود',
    'approved'   => 'كشف الموافق عليهم',
    'rejected'   => 'كشف المرفوضين',
    'reserve'    => 'كشف الاحتياط',
    'waiting'    => 'كشف الانتظار / المراجعة',
    'suspicious' => 'كشف الحالات المشتبه بها',
];

$rows = getStudySubmissions(1000);
$printRows = [];
foreach ($rows as $row) {
    $full = getSubmission((int)$row['id']) ?: $row;
    $merged = array_merge($row, $full);
    if (responsePrintMatchesView($merged, $view)) {
        $printRows[] = $merged;
    }
}

$orgName = function_exists('getSetting') ? (string)getSetting('org_name', 'لجنة زكاة وصدقات مخيم حطين') : 'لجنة زكاة وصدقات مخيم حطين';
$phone   = function_exists('getSetting') ? (string)getSetting('org_phone', '0096253613612') : '0096253613612';
$address = function_exists('getSetting') ? (string)getSetting('org_address', 'عمان الأردن - مخيم حطين') : 'عمان الأردن - مخيم حطين';
$title   = $viewTitles[$view] ?? 'كشف الردود';

if ($export === 'xls') {
    $fileName = 'study_' . $view . '_' . date('Ymd_His') . '.xls';
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Pragma: no-cache');
    header('Expires: 0');
    echo "\xEF\xBB\xBF";
    ?>
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head><meta charset="UTF-8"><title><?= hp($title) ?></title></head>
    <body>
    <table border="1">
        <thead>
        <tr>
            <th>م</th>
            <th>الاسم الرباعي</th>
            <th>الرقم الوطني</th>
            <th>رقم الهاتف</th>
            <th>التوقيع</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($printRows as $i => $row): ?>
            <tr>
                <td><?= $i + 1 ?></td>
                <td><?= hp((string)($row['full_name'] ?? '')) ?></td>
                <td><?= hp((string)($row['national_id'] ?? '')) ?></td>
                <td><?= hp((string)($row['phone'] ?? '')) ?></td>
                <td></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </body>
    </html>
    <?php
    exit;
}
?>
<!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>
@page { size: A4 portrait; margin: 10mm; }
*{box-sizing:border-box}
body{margin:0;background:#f3f6fb;color:#0f172a;font-family:Tahoma,Arial,sans-serif;font-size:12px;line-height:1.45}
.topbar{height:54px;background:#fff;border-bottom:1px solid #d9e2ef;display:flex;justify-content:flex-end;align-items:center;gap:10px;padding:0 20px;position:sticky;top:0;z-index:10}
.btn{border:1px solid #173a73;background:#173a73;color:#fff;border-radius:9px;padding:9px 15px;cursor:pointer;font-weight:900;text-decoration:none;display:inline-flex;align-items:center;gap:6px}.btn.light{background:#fff;color:#173a73}
.sheet{width:210mm;min-height:297mm;margin:0 auto;background:#fff;padding:7mm 7mm 9mm;box-shadow:0 6px 24px rgba(15,23,42,.12)}
.box{border:2px solid #102a5c;border-radius:12px;padding:8px 10px 10px;margin-bottom:7px;position:relative}
.header-grid{display:grid;grid-template-columns:1.15fr 2fr .7fr;gap:8px;align-items:start}.meta{font-size:11px;color:#334155;line-height:1.8}.org{text-align:center}.org h1{margin:0;font-size:21px;font-weight:900;color:#0f172a}.org .sub{font-size:11px;color:#64748b;border-bottom:1px solid #cbd5e1;padding-bottom:5px;margin-bottom:5px}.org h2{margin:0;font-size:15px;font-weight:900;color:#0f172a}.org h3{margin:0;font-size:14px;font-weight:900;color:#1d4ed8}.logo{width:38px;height:38px;border-radius:11px;background:#173a73;margin-inline-start:auto}.badge-title{position:absolute;right:10px;top:10px;background:#0f2347;color:#fff;border-radius:11px;padding:6px 14px;font-weight:900;font-size:12px}.page-no{position:absolute;right:14px;top:48px;color:#64748b;font-size:11px}.dist-info{border-top:1px dashed #cbd5e1;margin-top:7px;padding-top:7px;text-align:center;font-weight:900;font-size:12px;display:flex;gap:12px;justify-content:center;flex-wrap:wrap}.dist-info span{white-space:nowrap}
table{width:100%;border-collapse:collapse;table-layout:fixed}th,td{border:1.2px solid #111827;padding:5px 4px;text-align:center;vertical-align:middle;height:31px}th{background:#e8eef8;font-weight:900}.col-num{width:45px}.col-name{width:auto}.col-id{width:130px}.col-phone{width:112px}.col-sign{width:150px}.name{text-align:right;font-weight:900}.muted{color:#64748b}.footer-sign{display:grid;grid-template-columns:1fr 1fr 1fr;gap:18px;margin-top:16px;text-align:center;font-weight:900}.footer-sign div{border-top:1.5px solid #111827;padding-top:7px}
@media print{body{background:#fff}.topbar{display:none!important}.sheet{width:auto;min-height:auto;margin:0;padding:0;box-shadow:none}.box{break-inside:avoid}th{background:#e8eef8!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}}
</style>
</head>
<body>
<div class="topbar">
    <a class="btn light" href="admin.php?tab=responses">رجوع</a>
    <a class="btn light" href="response_print.php?view=<?= hp($view) ?>&export=xls">تصدير Excel</a>
    <button class="btn" onclick="window.print()">طباعة A4</button>
</div>

<div class="sheet">
    <div class="box">
        <div class="badge-title"><?= hp($title) ?></div>
        <div class="page-no">صفحة 1 / 1</div>
        <div class="header-grid">
            <div class="meta">
                <div><strong>تاريخ الطباعة:</strong> <?= hp(date('d-m-Y')) ?></div>
                <div><strong>الوقت:</strong> <?= hp(date('H:i')) ?></div>
                <div><strong>الهاتف:</strong> <?= hp($phone) ?></div>
                <div><strong>العنوان:</strong> <?= hp($address) ?></div>
            </div>
            <div class="org">
                <h1>لجنة الزكاة</h1>
                <div class="sub"><?= hp($orgName) ?> – هاتف: <?= hp($phone) ?></div>
                <h2>وزارة الأوقاف والشؤون والمقدسات الإسلامية</h2>
                <h2>صندوق الزكاة</h2>
                <h3><?= hp($orgName) ?></h3>
            </div>
            <div><div class="logo"></div></div>
        </div>
        <div class="dist-info">
            <span>عنوان الكشف: <?= hp($title) ?></span>
            <span>المصدر: الردود والقرارات</span>
            <span>عدد الأسماء: <?= (int)count($printRows) ?></span>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th class="col-num">الرقم</th>
                <th class="col-name">الاسم الكامل</th>
                <th class="col-id">رقم الهوية</th>
                <th class="col-phone">رقم الهاتف</th>
                <th class="col-sign">التوقيع</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($printRows as $i => $row): ?>
            <tr>
                <td><?= $i + 1 ?></td>
                <td class="name"><?= hp((string)($row['full_name'] ?? '')) ?></td>
                <td><?= hp((string)($row['national_id'] ?? '')) ?></td>
                <td><?= hp((string)($row['phone'] ?? '')) ?></td>
                <td></td>
            </tr>
            <?php endforeach; ?>
            <?php if (!$printRows): ?>
            <tr><td colspan="5" class="muted">لا توجد بيانات مطابقة لهذا القسم.</td></tr>
            <?php endif; ?>
            <?php
            $minRows = 18;
            $blankRows = max(0, $minRows - count($printRows));
            for ($i = 0; $i < $blankRows; $i++): ?>
            <tr><td></td><td></td><td></td><td></td><td></td></tr>
            <?php endfor; ?>
        </tbody>
    </table>

    <div class="footer-sign">
        <div>مسؤول الكشف</div>
        <div>المحاسب / المدقق</div>
        <div>رئيس اللجنة</div>
    </div>
</div>
</body>
</html>
