<?php
/**
 * الزيارات المنزلية - طلب واستقبال وإدارة
 */
use App\Core\Auth;
use App\Core\Tenant;

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

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

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

if ($action === 'update_status' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('orders.create')) {
    $reqId = (int)($_POST['request_id'] ?? 0);
    $newStatus = $_POST['status'] ?? '';
    if ($reqId > 0 && in_array($newStatus, ['pending', 'confirmed', 'completed', 'cancelled'], true)) {
        try {
            $db->prepare('UPDATE home_visit_requests SET status = ? WHERE id = ?')->execute([$newStatus, $reqId]);
            $_SESSION['home_visit_msg'] = 'تم تحديث الحالة.';
        } catch (Throwable $e) {}
    }
    $redir = 'index.php?page=home_visits';
    if (!empty($_GET['status'])) $redir .= '&status=' . urlencode($_GET['status']);
    if (!empty($_GET['q'])) $redir .= '&q=' . urlencode($_GET['q']);
    if (!empty($_GET['date_from'])) $redir .= '&date_from=' . urlencode($_GET['date_from']);
    if (!empty($_GET['date_to'])) $redir .= '&date_to=' . urlencode($_GET['date_to']);
    if (!empty($_GET['p']) && (int)$_GET['p'] > 1) $redir .= '&p=' . (int)$_GET['p'];
    header('Location: ' . $redir);
    exit;
}

$statusFilter = trim($_GET['status'] ?? '');
$searchQ = trim($_GET['q'] ?? '');
$dateFrom = trim($_GET['date_from'] ?? '');
$dateTo = trim($_GET['date_to'] ?? '');
$pageNum = max(1, (int)($_GET['p'] ?? 1));
$perPage = 25;
$offset = ($pageNum - 1) * $perPage;

$whereClause = ' (h.tenant_id = ? OR h.tenant_id IS NULL) ';
$params = [$tenantId];
if ($statusFilter !== '' && in_array($statusFilter, ['pending','confirmed','completed','cancelled'], true)) {
    $whereClause .= ' AND h.status = ? ';
    $params[] = $statusFilter;
}
if ($searchQ !== '') {
    $whereClause .= ' AND (h.patient_name LIKE ? OR h.patient_phone LIKE ? OR h.address LIKE ?) ';
    $like = '%' . $searchQ . '%';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}
if ($dateFrom !== '') {
    $whereClause .= ' AND h.visit_date >= ? ';
    $params[] = $dateFrom;
}
if ($dateTo !== '') {
    $whereClause .= ' AND h.visit_date <= ? ';
    $params[] = $dateTo;
}

$stats = ['total' => 0, 'pending' => 0, 'confirmed' => 0, 'completed' => 0];
try {
    $db->query('SELECT id FROM home_visit_requests LIMIT 1');
    $baseWhere = ' (tenant_id = ? OR tenant_id IS NULL) ';
    $baseParams = [$tenantId];
    $stmt = $db->prepare('SELECT COUNT(*) FROM home_visit_requests WHERE ' . $baseWhere);
    $stmt->execute($baseParams);
    $stats['total'] = (int)$stmt->fetchColumn();
    foreach (['pending','confirmed','completed','cancelled'] as $s) {
        $stmt = $db->prepare('SELECT COUNT(*) FROM home_visit_requests WHERE ' . $baseWhere . ' AND status = ?');
        $stmt->execute(array_merge($baseParams, [$s]));
        $stats[$s] = (int)$stmt->fetchColumn();
    }
} catch (Throwable $e) {}

$requests = [];
$totalCount = 0;
try {
    $db->query('SELECT id FROM home_visit_requests LIMIT 1');
    $stmt = $db->prepare('SELECT COUNT(*) FROM home_visit_requests h WHERE ' . $whereClause);
    $stmt->execute($params);
    $totalCount = (int)$stmt->fetchColumn();
    $limitOffset = ' LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
    $stmt = $db->prepare('SELECT h.*, o.order_number FROM home_visit_requests h LEFT JOIN lab_orders o ON o.id = h.order_id WHERE ' . $whereClause . ' ORDER BY h.visit_date DESC, h.id DESC' . $limitOffset);
    $stmt->execute($params);
    $requests = $stmt->fetchAll();
} catch (Throwable $e) {
    try {
        $stmt = $db->prepare('SELECT h.*, o.order_number FROM home_visit_requests h LEFT JOIN lab_orders o ON o.id = h.order_id WHERE (h.tenant_id = ? OR h.tenant_id IS NULL) ORDER BY h.visit_date DESC, h.id DESC LIMIT 100');
        $stmt->execute([$tenantId]);
        $requests = $stmt->fetchAll();
        $totalCount = count($requests);
    } catch (Throwable $e2) {}
}

$totalPages = $totalCount > 0 ? (int)ceil($totalCount / $perPage) : 1;
$statusLabels = ['pending' => 'معلق', 'confirmed' => 'مؤكد', 'completed' => 'مكتمل', 'cancelled' => 'ملغى'];
$baseUrl = 'index.php?page=home_visits' . ($searchQ ? '&q=' . urlencode($searchQ) : '') . ($statusFilter ? '&status=' . urlencode($statusFilter) : '') . ($dateFrom ? '&date_from=' . urlencode($dateFrom) : '') . ($dateTo ? '&date_to=' . urlencode($dateTo) : '');
$formRequestUrl = 'index.php?page=home_visit_request';
if ((int)$tenantId !== 1) {
    try {
        $tr = $db->prepare('SELECT slug FROM tenants WHERE id = ? LIMIT 1');
        $tr->execute([$tenantId]);
        if (($tRow = $tr->fetch()) && !empty($tRow['slug'])) {
            $formRequestUrl .= '&tenant=' . urlencode($tRow['slug']);
        }
    } catch (Throwable $e) {}
}
?>
<div class="page-header">
    <h1>طلبات الزيارات المنزلية</h1>
    <a href="<?php echo htmlspecialchars($formRequestUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" class="btn-secondary">📋 نموذج الطلب</a>
</div>
<?php if (!empty($_SESSION['home_visit_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['home_visit_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['home_visit_msg']); ?></div>
<?php endif; ?>

<section class="patients-stats" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:16px;margin-bottom:20px;">
    <div class="patients-stat-card">
        <span class="patients-stat-value"><?php echo $stats['total']; ?></span>
        <span class="patients-stat-label">الإجمالي</span>
    </div>
    <div class="patients-stat-card" style="border-right-color:var(--status-pending);">
        <span class="patients-stat-value"><?php echo $stats['pending']; ?></span>
        <span class="patients-stat-label"><a href="index.php?page=home_visits&status=pending" style="color:inherit;text-decoration:none;">معلق</a></span>
    </div>
    <div class="patients-stat-card" style="border-right-color:#3b82f6;">
        <span class="patients-stat-value"><?php echo $stats['confirmed']; ?></span>
        <span class="patients-stat-label"><a href="index.php?page=home_visits&status=confirmed" style="color:inherit;text-decoration:none;">مؤكد</a></span>
    </div>
    <div class="patients-stat-card" style="border-right-color:var(--status-completed);">
        <span class="patients-stat-value"><?php echo $stats['completed']; ?></span>
        <span class="patients-stat-label"><a href="index.php?page=home_visits&status=completed" style="color:inherit;text-decoration:none;">مكتمل</a></span>
    </div>
</section>

<form method="get" class="form-grid" style="margin-bottom:20px;display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
    <input type="hidden" name="page" value="home_visits">
    <div><label>بحث</label><input type="search" name="q" placeholder="الاسم، الهاتف، العنوان..." value="<?php echo htmlspecialchars($searchQ, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;"></div>
    <div><label>الحالة</label><select name="status"><option value="">— الكل —</option><?php foreach ($statusLabels as $k => $l): ?><option value="<?php echo $k; ?>" <?php echo $statusFilter === $k ? 'selected' : ''; ?>><?php echo $l; ?></option><?php endforeach; ?></select></div>
    <div><label>من تاريخ</label><input type="date" name="date_from" value="<?php echo htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8'); ?>"></div>
    <div><label>إلى تاريخ</label><input type="date" name="date_to" value="<?php echo htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8'); ?>"></div>
    <div><button type="submit" class="btn-primary">بحث</button> <?php if ($searchQ || $statusFilter || $dateFrom || $dateTo): ?><a href="index.php?page=home_visits" class="btn-secondary">مسح</a><?php endif; ?></div>
</form>

<div class="section-card">
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>المريض</th>
                    <th>الهاتف</th>
                    <th>العنوان</th>
                    <th>تاريخ الزيارة</th>
                    <th>الوقت</th>
                    <th>الحالة</th>
                    <th>الطلب</th>
                    <th style="min-width:180px;">إجراء</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($requests as $r): ?>
                <tr>
                    <td><?php echo (int)$r['id']; ?></td>
                    <td><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?><?php if (!empty(trim($r['notes'] ?? ''))): ?> <span title="<?php echo htmlspecialchars($r['notes'], ENT_QUOTES, 'UTF-8'); ?>" style="cursor:help;opacity:0.7;">📝</span><?php endif; ?></td>
                    <td><?php echo htmlspecialchars($r['patient_phone'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td style="max-width:180px;"><?php echo htmlspecialchars($r['address'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($r['visit_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars(($r['visit_time_start'] ?? '') . ($r['visit_time_end'] ? ' - ' . $r['visit_time_end'] : ''), ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><span class="badge badge-<?php echo $r['status']; ?>"><?php echo $statusLabels[$r['status']] ?? $r['status']; ?></span></td>
                    <td><?php echo $r['order_number'] ? htmlspecialchars($r['order_number'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
                    <td>
                        <?php if ($auth->can('orders.create') && $r['status'] !== 'completed' && $r['status'] !== 'cancelled'): ?>
                        <form method="post" action="index.php?page=home_visits&action=update_status<?php echo $statusFilter ? '&status='.urlencode($statusFilter) : ''; ?><?php echo $searchQ ? '&q='.urlencode($searchQ) : ''; ?><?php echo $dateFrom ? '&date_from='.urlencode($dateFrom) : ''; ?><?php echo $dateTo ? '&date_to='.urlencode($dateTo) : ''; ?><?php echo $pageNum > 1 ? '&p='.$pageNum : ''; ?>" style="display:inline;">
                            <input type="hidden" name="request_id" value="<?php echo (int)$r['id']; ?>">
                            <select name="status" onchange="this.form.submit()" style="padding:4px 8px;">
                                <?php foreach ($statusLabels as $k => $l): ?>
                                <option value="<?php echo $k; ?>" <?php echo $r['status'] === $k ? 'selected' : ''; ?>><?php echo $l; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </form>
                        <?php endif; ?>
                        <?php if ($auth->can('orders.create') && !$r['order_id'] && $r['patient_id']): ?><a href="index.php?page=orders&action=create&patient_id=<?php echo (int)$r['patient_id']; ?>" class="btn-action btn-action--order" title="إنشاء طلب">طلب</a><?php endif; ?>
                        <?php if ($r['patient_id']): ?><a href="index.php?page=patients&action=view&id=<?php echo (int)$r['patient_id']; ?>" class="btn-link">ملف</a><?php endif; ?>
                        <?php if ($r['order_id']): ?><a href="index.php?page=results&order_id=<?php echo (int)$r['order_id']; ?>" class="btn-link">نتائج</a><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (empty($requests)): ?>
    <p class="patients-empty"><?php echo ($searchQ || $statusFilter || $dateFrom || $dateTo) ? 'لا توجد نتائج تطابق البحث.' : 'لا توجد طلبات زيارات منزلية.'; ?> <?php if ($searchQ || $statusFilter || $dateFrom || $dateTo): ?><a href="index.php?page=home_visits">عرض الكل</a><?php endif; ?></p>
    <?php endif; ?>
</div>

<?php if ($totalPages > 1): ?>
<?php $pageBase = $baseUrl . (strpos($baseUrl, '?') !== false ? '&' : '?'); ?>
<nav class="patients-pagination" style="margin-top:20px;display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
    <?php if ($pageNum > 1): ?><a href="<?php echo $pageBase . 'p=' . ($pageNum - 1); ?>" class="btn-secondary">← السابق</a><?php endif; ?>
    <span style="color:var(--text-muted);">صفحة <?php echo $pageNum; ?> من <?php echo $totalPages; ?></span>
    <?php if ($pageNum < $totalPages): ?><a href="<?php echo $pageBase . 'p=' . ($pageNum + 1); ?>" class="btn-secondary">التالي →</a><?php endif; ?>
</nav>
<?php endif; ?>
