<?php
/**
 * حزم الفحوصات - باقات جاهزة (سكر، كبد، دهون، إلخ) بأسعار مخفضة
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';

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

$testTenantAnd = '';
try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
$pkgTenantAnd = '';
try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('tests.create')) {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        try {
            $db->prepare('DELETE FROM test_package_items WHERE package_id = ?')->execute([$id]);
            $db->prepare('DELETE FROM test_packages WHERE id = ?')->execute([$id]);
            $_SESSION['packages_msg'] = 'تم حذف الحزمة.';
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=packages');
    exit;
}

$hasIsActive = false;
try { $db->query('SELECT is_active FROM test_packages LIMIT 1'); $hasIsActive = true; } catch (Throwable $e) {}

if ($action === 'duplicate' && $_SERVER['REQUEST_METHOD'] === 'GET' && $auth->can('tests.create')) {
    $dupId = (int)($_GET['id'] ?? 0);
    if ($dupId > 0) {
        try {
            $cols = 'name, description, price';
            if ($hasIsActive) $cols .= ', is_active';
            try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $cols .= ', tenant_id'; } catch (Throwable $e) {}
            $row = $db->prepare('SELECT ' . $cols . ' FROM test_packages WHERE id = ?');
            $row->execute([$dupId]);
            $src = $row->fetch();
            if ($src) {
                $newName = trim($src['name']) . ' (نسخة)';
                $desc = $src['description'] ?? null;
                $pr = (float)($src['price'] ?? 0);
                $active = ($hasIsActive && isset($src['is_active'])) ? (int)$src['is_active'] : 1;
                $tid = isset($src['tenant_id']) ? (int)$src['tenant_id'] : $tenantId;
                $hasTenant = isset($src['tenant_id']);
                if ($hasIsActive && $hasTenant) {
                    $db->prepare('INSERT INTO test_packages (name, description, price, is_active, tenant_id) VALUES (?, ?, ?, ?, ?)')->execute([$newName, $desc, $pr, $active, $tid]);
                } elseif ($hasIsActive) {
                    $db->prepare('INSERT INTO test_packages (name, description, price, is_active) VALUES (?, ?, ?, ?)')->execute([$newName, $desc, $pr, $active]);
                } elseif ($hasTenant) {
                    $db->prepare('INSERT INTO test_packages (name, description, price, tenant_id) VALUES (?, ?, ?, ?)')->execute([$newName, $desc, $pr, $tid]);
                } else {
                    $db->prepare('INSERT INTO test_packages (name, description, price) VALUES (?, ?, ?, ?)')->execute([$newName, $desc, $pr]);
                }
                $newId = (int)$db->lastInsertId();
                $db->prepare('INSERT INTO test_package_items (package_id, test_id) SELECT ?, test_id FROM test_package_items WHERE package_id = ?')->execute([$newId, $dupId]);
                $_SESSION['packages_msg'] = 'تم نسخ الحزمة.';
                header('Location: index.php?page=packages&action=edit&id=' . $newId);
                exit;
            }
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=packages');
    exit;
}

if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('tests.create')) {
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    $testIds = isset($_POST['tests']) ? array_map('intval', (array)$_POST['tests']) : [];
    $testIds = array_values(array_filter($testIds, fn($v) => $v > 0));

    if ($name !== '' && $price >= 0) {
        try {
            $db->beginTransaction();
            if ($id > 0) {
                if ($hasIsActive) {
                    $db->prepare('UPDATE test_packages SET name = ?, description = ?, price = ?, is_active = ? WHERE id = ?')->execute([$name, $description ?: null, $price, $isActive, $id]);
                } else {
                    $db->prepare('UPDATE test_packages SET name = ?, description = ?, price = ? WHERE id = ?')->execute([$name, $description ?: null, $price, $id]);
                }
                $db->prepare('DELETE FROM test_package_items WHERE package_id = ?')->execute([$id]);
            } else {
                if ($hasIsActive) {
                    $db->prepare('INSERT INTO test_packages (name, description, price, is_active, tenant_id) VALUES (?, ?, ?, ?, ?)')->execute([$name, $description ?: null, $price, $isActive, $tenantId]);
                } else {
                    $db->prepare('INSERT INTO test_packages (name, description, price, tenant_id) VALUES (?, ?, ?, ?)')->execute([$name, $description ?: null, $price, $tenantId]);
                }
                $id = (int)$db->lastInsertId();
            }
            foreach ($testIds as $tid) {
                $db->prepare('INSERT INTO test_package_items (package_id, test_id) VALUES (?, ?)')->execute([$id, $tid]);
            }
            $db->commit();
            $_SESSION['packages_msg'] = 'تم حفظ الحزمة.';
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
        }
    }
    header('Location: index.php?page=packages');
    exit;
}

$searchQ = trim($_GET['q'] ?? '');
$statusFilter = trim($_GET['status'] ?? ''); // active, inactive, or empty=all
$whereClause = ' 1=1 ' . $pkgTenantAnd;
$params = [];
if ($searchQ !== '') {
    $whereClause .= ' AND (name LIKE ? OR description LIKE ?) ';
    $like = '%' . $searchQ . '%';
    $params[] = $like;
    $params[] = $like;
}
if ($statusFilter === 'active') {
    if ($hasIsActive) { $whereClause .= ' AND is_active = 1 '; }
} elseif ($statusFilter === 'inactive') {
    if ($hasIsActive) { $whereClause .= ' AND is_active = 0 '; }
}

$packages = [];
try {
    $db->query('SELECT id FROM test_packages LIMIT 1');
    $sql = 'SELECT * FROM test_packages WHERE ' . $whereClause . ' ORDER BY name';
    if (count($params) > 0) {
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $packages = $stmt->fetchAll();
    } else {
        $packages = $db->query($sql)->fetchAll();
    }
} catch (Throwable $e) {}

foreach ($packages as &$p) {
    $st = $db->prepare('SELECT t.id, t.name, t.test_code, t.default_price FROM tests t JOIN test_package_items tpi ON tpi.test_id = t.id WHERE tpi.package_id = ? ORDER BY t.name');
    $st->execute([$p['id']]);
    $p['tests'] = $st->fetchAll();
    $singleSum = 0;
    foreach ($p['tests'] ?? [] as $t) { $singleSum += (float)($t['default_price'] ?? 0); }
    $p['single_sum'] = $singleSum;
}
unset($p);

$stats = ['total' => 0, 'active' => 0, 'inactive' => 0];
try {
    $stmt = $db->prepare('SELECT COUNT(*) FROM test_packages WHERE 1=1' . $pkgTenantAnd);
    $stmt->execute();
    $stats['total'] = (int)$stmt->fetchColumn();
    if ($hasIsActive) {
        $stmt = $db->prepare('SELECT COUNT(*) FROM test_packages WHERE is_active = 1' . $pkgTenantAnd);
        $stmt->execute();
        $stats['active'] = (int)$stmt->fetchColumn();
        $stats['inactive'] = $stats['total'] - $stats['active'];
    }
} catch (Throwable $e) {}

$allTests = [];
try {
    $stmt = $db->query('SELECT id, name, test_code, default_price FROM tests WHERE 1=1' . $testTenantAnd . ' ORDER BY name');
    $allTests = $stmt->fetchAll();
} catch (Throwable $e) {}

$baseUrl = 'index.php?page=packages' . ($searchQ ? '&q=' . urlencode($searchQ) : '') . ($statusFilter ? '&status=' . urlencode($statusFilter) : '');
?>
<div class="page-header">
    <h1>📦 حزم الفحوصات</h1>
    <?php if ($auth->can('tests.create')): ?><a href="index.php?page=packages&action=edit" class="btn-primary">+ حزمة جديدة</a><?php endif; ?>
</div>

<?php if (!empty($_SESSION['packages_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['packages_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['packages_msg']); ?></div>
<?php endif; ?>

<?php if ($action !== 'edit'): ?>
<div class="stats-cards" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:16px;">
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px;">
        <div style="color:var(--text-muted);font-size:0.85em;">الإجمالي</div>
        <div style="font-size:1.4em;font-weight:600;"><?php echo $stats['total']; ?></div>
    </div>
    <?php if ($hasIsActive): ?>
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px;">
        <div style="color:var(--text-muted);font-size:0.85em;">نشط</div>
        <div style="font-size:1.4em;font-weight:600;color:var(--success);"><?php echo $stats['active']; ?></div>
    </div>
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px;">
        <div style="color:var(--text-muted);font-size:0.85em;">غير نشط</div>
        <div style="font-size:1.4em;font-weight:600;color:var(--text-muted);"><?php echo $stats['inactive']; ?></div>
    </div>
    <?php endif; ?>
</div>
<form method="get" class="filters-bar" style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:16px;">
    <input type="hidden" name="page" value="packages">
    <input type="search" name="q" placeholder="بحث باسم الحزمة أو الوصف..." value="<?php echo htmlspecialchars($searchQ, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;">
    <?php if ($hasIsActive): ?>
    <select name="status" onchange="this.form.submit()">
        <option value="">كل الحزم</option>
        <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>نشط فقط</option>
        <option value="inactive" <?php echo $statusFilter === 'inactive' ? 'selected' : ''; ?>>غير نشط فقط</option>
    </select>
    <?php endif; ?>
    <button type="submit" class="btn-secondary">بحث</button>
    <?php if ($searchQ !== '' || $statusFilter !== ''): ?><a href="index.php?page=packages" class="btn-secondary">إزالة الفلتر</a><?php endif; ?>
</form>
<?php endif; ?>

<?php if ($action === 'edit'): ?>
<?php
$editId = (int)($_GET['id'] ?? 0);
$edit = null;
if ($editId > 0) {
    foreach ($packages as $p) { if ((int)$p['id'] === $editId) { $edit = $p; break; } }
    if (!$edit) {
        try {
            $st = $db->prepare('SELECT * FROM test_packages WHERE id = ?' . $pkgTenantAnd);
            $st->execute([$editId]);
            $edit = $st->fetch();
            if ($edit) {
                $st2 = $db->prepare('SELECT t.id, t.name, t.test_code, t.default_price FROM tests t JOIN test_package_items tpi ON tpi.test_id = t.id WHERE tpi.package_id = ? ORDER BY t.name');
                $st2->execute([$editId]);
                $edit['tests'] = $st2->fetchAll();
                $singleSum = 0;
                foreach ($edit['tests'] ?? [] as $t) { $singleSum += (float)($t['default_price'] ?? 0); }
                $edit['single_sum'] = $singleSum;
            }
        } catch (Throwable $e) {}
        if (!$edit) {
            $st = $db->prepare('SELECT * FROM test_packages WHERE id = ?');
            $st->execute([$editId]);
            $edit = $st->fetch();
            if ($edit) {
                $st2 = $db->prepare('SELECT t.id, t.name, t.test_code, t.default_price FROM tests t JOIN test_package_items tpi ON tpi.test_id = t.id WHERE tpi.package_id = ? ORDER BY t.name');
                $st2->execute([$editId]);
                $edit['tests'] = $st2->fetchAll();
                $edit['single_sum'] = 0;
            }
        }
    }
}
?>
<div class="section-card">
    <h2><?php echo $edit ? 'تعديل الحزمة' : 'حزمة جديدة'; ?></h2>
    <form method="post" action="index.php?page=packages&action=save" class="form-grid package-form">
        <input type="hidden" name="id" value="<?php echo $edit ? (int)$edit['id'] : 0; ?>">
        <div class="form-group">
            <label for="pkg-name">اسم الحزمة <span class="required">*</span></label>
            <input type="text" id="pkg-name" name="name" required value="<?php echo htmlspecialchars($edit['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثل: فحوصات السكر الكاملة">
        </div>
        <div class="form-group">
            <label for="pkg-price">السعر (بالمجموع) <span class="required">*</span></label>
            <input type="number" id="pkg-price" name="price" step="0.01" min="0" required value="<?php echo htmlspecialchars($edit['price'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>" placeholder="0">
        </div>
        <div class="form-group full-width">
            <label for="pkg-desc">الوصف</label>
            <textarea id="pkg-desc" name="description" rows="2" placeholder="وصف مختصر للحزمة (اختياري)"><?php echo htmlspecialchars($edit['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
        </div>
        <?php if ($hasIsActive): ?>
        <div class="form-group">
            <label class="checkbox-label">
                <input type="checkbox" name="is_active" value="1" <?php echo ($edit['is_active'] ?? 1) ? 'checked' : ''; ?>>
                <span>حزمة نشطة (متاحة للاستخدام)</span>
            </label>
        </div>
        <?php endif; ?>
        <div class="form-group full-width package-tests-section">
            <label for="packageTestsSearch">الفحوصات المضمنة</label>
            <input type="search" id="packageTestsSearch" class="package-tests-search" placeholder="ابحث بالاسم أو الكود...">
            <small class="package-list-hint">مرّر داخل القائمة لعرض جميع الفحوصات — أزرار الحفظ أدناه</small>
            <div id="packageTestsList" class="package-tests-list" style="height:280px;max-height:280px;overflow-y:auto;overflow-x:hidden;">
            <?php foreach ($allTests as $t): ?>
                <label class="package-test-item">
                    <input type="checkbox" name="tests[]" value="<?php echo (int)$t['id']; ?>"
                        <?php echo $edit && in_array((int)$t['id'], array_column($edit['tests'] ?? [], 'id')) ? 'checked' : ''; ?>>
                    <span class="test-name"><?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <span class="test-meta"><?php echo htmlspecialchars($t['test_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?> — <?php echo number_format($t['default_price'] ?? 0); ?></span>
                </label>
            <?php endforeach; ?>
            </div>
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ</button>
            <a href="<?php echo htmlspecialchars($baseUrl, ENT_QUOTES, 'UTF-8'); ?>" class="btn-secondary">إلغاء</a>
        </div>
    </form>
</div>
<script>
(function(){
    var list = document.getElementById('packageTestsList');
    var searchInput = document.getElementById('packageTestsSearch');
    if (list && searchInput) {
        searchInput.addEventListener('input', function(){
            var q = (this.value || '').trim().toLowerCase();
            list.querySelectorAll('.package-test-item').forEach(function(label){
                var text = (label.textContent || '').toLowerCase();
                label.style.display = q === '' || text.indexOf(q) >= 0 ? '' : 'none';
            });
        });
    }
})();
</script>
<?php else: ?>
<div class="section-card">
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>الحزمة</th>
                    <th>الفحوصات</th>
                    <th>السعر</th>
                    <?php if ($hasIsActive): ?><th>الحالة</th><?php endif; ?>
                    <th>التوفير</th>
                    <th>إجراء</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($packages as $p): ?>
                <?php
                $singleSum = (float)($p['single_sum'] ?? 0);
                $pkgPrice = (float)($p['price'] ?? 0);
                $savings = $singleSum > 0 && $pkgPrice < $singleSum ? ($singleSum - $pkgPrice) : 0;
                $pkgActive = ($p['is_active'] ?? 1);
                ?>
                <tr>
                    <td>
                        <strong><?php echo htmlspecialchars($p['name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                        <?php if (!empty($p['description'])): ?><br><small style="color:var(--text-muted);"><?php echo htmlspecialchars($p['description'], ENT_QUOTES, 'UTF-8'); ?></small><?php endif; ?>
                    </td>
                    <td>
                        <?php
                        $tnames = array_column($p['tests'] ?? [], 'name');
                        echo htmlspecialchars(implode('، ', $tnames) ?: '—', ENT_QUOTES, 'UTF-8');
                        ?>
                    </td>
                    <td><?php echo number_format($p['price'] ?? 0); ?></td>
                    <?php if ($hasIsActive): ?>
                    <td><span class="badge badge-<?php echo $pkgActive ? 'completed' : 'cancelled'; ?>"><?php echo $pkgActive ? 'نشط' : 'غير نشط'; ?></span></td>
                    <?php endif; ?>
                    <td>
                        <?php if ($savings > 0): ?>
                            <span style="color:var(--success);" title="القيمة المنفردة: <?php echo number_format($singleSum); ?>"><?php echo number_format($savings); ?> ✓</span>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td>
                        <?php if ($auth->can('orders.create') && $pkgActive): ?>
                        <a href="index.php?page=orders&action=create&package_id=<?php echo (int)$p['id']; ?>" class="btn-action" style="background:var(--primary);color:#fff;">استخدام</a>
                        <?php endif; ?>
                        <?php if ($auth->can('tests.create')): ?>
                        <a href="index.php?page=packages&action=edit&id=<?php echo (int)$p['id']; ?>" class="btn-action btn-action--edit">تعديل</a>
                        <a href="index.php?page=packages&action=duplicate&id=<?php echo (int)$p['id']; ?>" class="btn-action btn-action--edit" title="نسخ الحزمة">نسخ</a>
                        <form method="post" action="index.php?page=packages&action=delete" style="display:inline;" onsubmit="return confirm('حذف هذه الحزمة؟');">
                            <input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>">
                            <button type="submit" class="btn-action btn-action--delete">حذف</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (empty($packages)): ?>
    <p class="patients-empty">لا توجد حزم فحوصات. <a href="index.php?page=packages&action=edit">إنشاء حزمة جديدة</a></p>
    <?php endif; ?>
</div>
<?php endif; ?>
