<?php
/**
 * إدارة طلبات الفحوصات - نسخة مطورة
 */
use App\Core\Auth;
use App\Core\Tenant;

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

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

// معالجة تحديث حالة الطلب
if ($action === 'update_status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $orderId = (int)($_POST['order_id'] ?? 0);
    $newStatus = trim($_POST['status'] ?? '');
    $newPriority = in_array($_POST['priority'] ?? '', ['normal','urgent','high']) ? $_POST['priority'] : null;
    
    if ($orderId > 0 && in_array($newStatus, ['new', 'in_progress', 'completed', 'cancelled'])) {
        try {
            $stmt = $db->prepare('SELECT id, status FROM lab_orders WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$orderId, $tenantId]);
            $order = $stmt->fetch();
            
            if ($order) {
                $oldStatus = $order['status'];
                $updSql = 'UPDATE lab_orders SET status = ?';
                $updParams = [$newStatus];
                if ($newPriority !== null) {
                    try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $updSql .= ', priority = ?'; $updParams[] = $newPriority; } catch (Throwable $e) {}
                }
                $updSql .= ' WHERE id = ? AND tenant_id = ?';
                $updParams[] = $orderId;
                $updParams[] = $tenantId;
                $db->prepare($updSql)->execute($updParams);
                if (isset($auditLog)) {
                    $auditLog->log(
                        'order_status_updated',
                        'lab_order',
                        $orderId,
                        json_encode(['status' => $oldStatus], JSON_UNESCAPED_UNICODE),
                        json_encode(['status' => $newStatus], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['orders_msg'] = 'تم تحديث حالة الطلب بنجاح';
            }
        } catch (Throwable $e) {
            $_SESSION['orders_error'] = 'حدث خطأ أثناء تحديث حالة الطلب';
        }
    }
    header('Location: index.php?page=orders&action=view&id=' . $orderId);
    exit;
}

// معالجة إلغاء الطلب
if ($action === 'cancel' && isset($_GET['id'])) {
    $orderId = (int)$_GET['id'];
    if ($orderId > 0) {
        try {
            $stmt = $db->prepare('SELECT id, status FROM lab_orders WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$orderId, $tenantId]);
            $order = $stmt->fetch();
            
            if ($order && $order['status'] !== 'cancelled') {
                $stmt = $db->prepare('UPDATE lab_orders SET status = ? WHERE id = ? AND tenant_id = ?');
                $stmt->execute(['cancelled', $orderId, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'order_cancelled',
                        'lab_order',
                        $orderId,
                        json_encode(['status' => $order['status']], JSON_UNESCAPED_UNICODE),
                        json_encode(['status' => 'cancelled'], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['orders_msg'] = 'تم إلغاء الطلب بنجاح';
            }
        } catch (Throwable $e) {
            $_SESSION['orders_error'] = 'حدث خطأ أثناء إلغاء الطلب';
        }
    }
    header('Location: index.php?page=orders');
    exit;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('orders.create')) {
        http_response_code(403);
        echo 'غير مسموح بإنشاء الطلبات';
        return;
    }
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $doctorId = (int)($_POST['doctor_id'] ?? 0);
    $branchId = (int)($_POST['branch_id'] ?? 0);
    $packageId = (int)($_POST['package_id'] ?? 0);
    $priority = in_array($_POST['priority'] ?? '', ['normal','urgent','high']) ? $_POST['priority'] : 'normal';
    $testIds = $_POST['tests'] ?? [];

    if ($packageId > 0) {
        try {
            $pkgTenantAnd = '';
            $pkgParams = [$packageId];
            try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenantAnd = ' AND tenant_id = ?'; $pkgParams[] = $tenantId; } catch (Throwable $e) {}
            $pStmt = $db->prepare('SELECT id, price FROM test_packages WHERE id = ?' . $pkgTenantAnd);
            $pStmt->execute($pkgParams);
            $pkg = $pStmt->fetch();
            if ($pkg) {
                $st = $db->prepare('SELECT test_id FROM test_package_items WHERE package_id = ?');
                $st->execute([$packageId]);
                $testIds = array_values(array_filter(array_map(fn($r) => (int)$r['test_id'], $st->fetchAll()), fn($v) => $v > 0));
            } else {
                $packageId = 0;
            }
        } catch (Throwable $e) {}
    }

    if ($branchId <= 0) {
        $userBranchId = ($auth instanceof Auth) ? $auth->branchId() : null;
        $branchId = $userBranchId !== null ? $userBranchId : 1;
    }
    if ($patientId > 0 && is_array($testIds) && count($testIds) > 0) {
        $testIds = array_map('intval', $testIds);
        $testIds = array_values(array_filter($testIds, fn($v) => $v > 0));

        if (count($testIds) > 0) {
            $userId = $auth instanceof Auth ? $auth->userId() : null;
            if ($userId === null || $userId <= 0) {
                header('Location: index.php?page=login');
                exit;
            }

            try {
                // تحقق من انتماء المريض/الطبيب/الفرع لنفس المختبر عند توفر tenant_id
                try {
                    $db->query('SELECT tenant_id FROM patients LIMIT 1');
                    $stmt = $db->prepare('SELECT id FROM patients WHERE id = ? AND tenant_id = ?');
                    $stmt->execute([$patientId, $tenantId]);
                    if (!$stmt->fetch()) {
                        $_SESSION['orders_error'] = 'المريض غير موجود لهذا المختبر.';
                        header('Location: index.php?page=orders&action=create');
                        exit;
                    }
                } catch (Throwable $e) {}
                if ($doctorId > 0) {
                    try {
                        $db->query('SELECT tenant_id FROM doctors LIMIT 1');
                        $stmt = $db->prepare('SELECT id FROM doctors WHERE id = ? AND tenant_id = ?');
                        $stmt->execute([$doctorId, $tenantId]);
                        if (!$stmt->fetch()) {
                            $doctorId = 0;
                        }
                    } catch (Throwable $e) {}
                }
                if ($branchId > 0) {
                    try {
                        $db->query('SELECT tenant_id FROM branches LIMIT 1');
                        $stmt = $db->prepare('SELECT id FROM branches WHERE id = ? AND tenant_id = ?');
                        $stmt->execute([$branchId, $tenantId]);
                        if (!$stmt->fetch()) {
                            $_SESSION['orders_error'] = 'الفرع غير صالح لهذا المختبر.';
                            header('Location: index.php?page=orders&action=create');
                            exit;
                        }
                    } catch (Throwable $e) {}
                }

                $db->beginTransaction();

                $orderNumber = 'O' . time();

                $branchName = null;
                $branchTenantAnd = '';
                $branchParams = [$branchId];
                try { $db->query('SELECT tenant_id FROM branches LIMIT 1'); $branchTenantAnd = ' AND tenant_id = ?'; $branchParams[] = $tenantId; } catch (Throwable $e) {}
                $bStmt = $db->prepare('SELECT name FROM branches WHERE id = ?' . $branchTenantAnd);
                $bStmt->execute($branchParams);
                if ($bRow = $bStmt->fetch()) $branchName = $bRow['name'];

                $hasPriority = false;
                try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriority = true; } catch (Throwable $e) {}
                try {
                    if ($hasPriority) {
                        $stmt = $db->prepare('INSERT INTO lab_orders (order_number, patient_id, doctor_id, order_date, status, priority, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by, tenant_id) VALUES (:num, :pid, :doc, NOW(), :status, :priority, 0, 0, 0, :pay_status, :branch_id, :branch_name, :created_by, :tid)');
                        $stmt->execute(['num' => $orderNumber, 'pid' => $patientId, 'doc' => $doctorId > 0 ? $doctorId : null, 'status' => 'new', 'priority' => $priority, 'pay_status' => 'unpaid', 'branch_id' => $branchId, 'branch_name' => $branchName, 'created_by' => $userId, 'tid' => $tenantId]);
                    } else {
                        $stmt = $db->prepare('INSERT INTO lab_orders (order_number, patient_id, doctor_id, order_date, status, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by, tenant_id) VALUES (:num, :pid, :doc, NOW(), :status, 0, 0, 0, :pay_status, :branch_id, :branch_name, :created_by, :tid)');
                        $stmt->execute(['num' => $orderNumber, 'pid' => $patientId, 'doc' => $doctorId > 0 ? $doctorId : null, 'status' => 'new', 'pay_status' => 'unpaid', 'branch_id' => $branchId, 'branch_name' => $branchName, 'created_by' => $userId, 'tid' => $tenantId]);
                    }
                } catch (Throwable $ex) {
                    $stmt = $db->prepare('INSERT INTO lab_orders (order_number, patient_id, doctor_id, order_date, status, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by) VALUES (:num, :pid, :doc, NOW(), :status, 0, 0, 0, :pay_status, :branch_id, :branch_name, :created_by)');
                    $stmt->execute(['num' => $orderNumber, 'pid' => $patientId, 'doc' => $doctorId > 0 ? $doctorId : null, 'status' => 'new', 'pay_status' => 'unpaid', 'branch_id' => $branchId, 'branch_name' => $branchName, 'created_by' => $userId]);
                }

                $orderId = (int)$db->lastInsertId();

                $placeholders = implode(',', array_fill(0, count($testIds), '?'));
                $testTenantAnd = '';
                $testParams = $testIds;
                try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND tenant_id = ?'; $testParams[] = $tenantId; } catch (Throwable $e) {}
                $stmt = $db->prepare("SELECT id, default_price, inventory_item_id, consumption_quantity FROM tests WHERE id IN ($placeholders)" . $testTenantAnd);
                $stmt->execute($testParams);
                $testRows = $stmt->fetchAll();
                if (count($testRows) !== count($testIds)) {
                    throw new Exception('tests_not_allowed');
                }

                $prices = [];
                $consumptions = [];
                $packagePrice = null;
                if ($packageId > 0 && count($testRows) > 0) {
                    $pkgTenantAnd = '';
                    $pkgParams = [$packageId];
                    try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenantAnd = ' AND tenant_id = ?'; $pkgParams[] = $tenantId; } catch (Throwable $e) {}
                    $pStmt = $db->prepare('SELECT price FROM test_packages WHERE id = ?' . $pkgTenantAnd);
                    $pStmt->execute($pkgParams);
                    $pr = $pStmt->fetch();
                    if ($pr && (float)($pr['price'] ?? 0) > 0) {
                        $packagePrice = (float)$pr['price'];
                    }
                }
                $defaultTotal = 0;
                foreach ($testRows as $row) {
                    $defaultTotal += (float)$row['default_price'];
                }
                foreach ($testRows as $row) {
                    $id = (int)$row['id'];
                    if ($packagePrice !== null && $packagePrice > 0 && $defaultTotal > 0) {
                        $prices[$id] = round($packagePrice * ((float)$row['default_price'] / $defaultTotal), 2);
                    } else {
                        $prices[$id] = (float)$row['default_price'];
                    }
                    $itemId = $row['inventory_item_id'] !== null ? (int)$row['inventory_item_id'] : null;
                    $qty = isset($row['consumption_quantity']) ? (float)$row['consumption_quantity'] : 0.0;
                    if ($itemId !== null && $qty > 0) {
                        $consumptions[$id] = [
                            'item_id' => $itemId,
                            'qty' => $qty
                        ];
                    }
                }

                $sampleCode = 'S' . time();
                $barcode = $sampleCode;
                try {
                    $db->query('SELECT barcode FROM samples LIMIT 1');
                    $stmt = $db->prepare('INSERT INTO samples (sample_code, barcode, order_id, sample_type, collection_datetime, received_datetime, status) VALUES (:code, :barcode, :order_id, :type, NOW(), NOW(), :status)');
                    $stmt->execute(['code' => $sampleCode, 'barcode' => $barcode, 'order_id' => $orderId, 'type' => 'blood', 'status' => 'received']);
                } catch (Throwable $ex) {
                    $stmt = $db->prepare('INSERT INTO samples (sample_code, order_id, sample_type, collection_datetime, received_datetime, status) VALUES (:code, :order_id, :type, NOW(), NOW(), :status)');
                    $stmt->execute(['code' => $sampleCode, 'order_id' => $orderId, 'type' => 'blood', 'status' => 'received']);
                }
                $sampleId = (int)$db->lastInsertId();

                $total = 0;
                $itemStmt = $db->prepare(
                    'INSERT INTO order_items (order_id, test_id, panel_id, sample_id, price, status)
                     VALUES (:order_id, :test_id, NULL, :sample_id, :price, :status)'
                );

                $movementStmt = $db->prepare(
                    'INSERT INTO inventory_movements (item_id, movement_date, movement_type, quantity, note, created_by)
                     VALUES (:item_id, NOW(), :type, :qty, :note, :created_by)'
                );
                $updateStockStmt = $db->prepare(
                    'UPDATE inventory_items
                     SET current_quantity = current_quantity - :qty
                     WHERE id = :id'
                );

                foreach ($testIds as $tid) {
                    if (!isset($prices[$tid])) {
                        continue;
                    }
                    $price = $prices[$tid];
                    $total += $price;

                    $itemStmt->execute([
                        'order_id' => $orderId,
                        'test_id' => $tid,
                        'sample_id' => $sampleId,
                        'price' => $price,
                        'status' => 'pending'
                    ]);

                    if (isset($consumptions[$tid])) {
                        $itemId = $consumptions[$tid]['item_id'];
                        $qty = $consumptions[$tid]['qty'];

                        $movementStmt->execute([
                            'item_id' => $itemId,
                            'type' => 'out',
                            'qty' => $qty,
                            'note' => 'استهلاك فحص من الطلب ' . $orderNumber,
                            'created_by' => $userId
                        ]);

                        $updateStockStmt->execute([
                            'qty' => $qty,
                            'id' => $itemId
                        ]);
                    }
                }

                $stmt = $db->prepare(
                    'UPDATE lab_orders
                     SET total_amount = :total, net_amount = :net
                     WHERE id = :id'
                );
                $stmt->execute([
                    'total' => $total,
                    'net' => $total,
                    'id' => $orderId
                ]);

                $db->commit();
                if (isset($auditLog)) {
                    $auditLog->log(
                        'order_created',
                        'lab_order',
                        $orderId,
                        null,
                        json_encode([
                            'order_number' => $orderNumber,
                            'patient_id' => $patientId,
                            'doctor_id' => $doctorId,
                            'tests' => $testIds,
                            'total' => $total
                        ], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['orders_msg'] = 'تم إنشاء الطلب بنجاح';
            } catch (Throwable $e) {
                if ($db->inTransaction()) {
                    $db->rollBack();
                }
                $_SESSION['orders_error'] = $e->getMessage() === 'tests_not_allowed' ? 'الفحوصات المختارة غير متاحة لهذا المختبر.' : 'حدث خطأ أثناء إنشاء الطلب';
            }
        }
    }

    header('Location: index.php?page=orders');
    exit;
}

if ($action === 'create') {
    $patients = [];
    $tests = [];
    $doctors = [];
    $branches = [];
    $reorderPatientId = (int)($_GET['patient_id'] ?? 0);
    $reorderDoctorId = (int)($_GET['doctor_id'] ?? 0);
    $reorderTests = isset($_GET['tests']) ? array_map('intval', (array)$_GET['tests']) : [];
    $reorderBranchId = (int)($_GET['branch_id'] ?? 0);
    $reorderPackageId = (int)($_GET['package_id'] ?? 0);
    $reorderId = (int)($_GET['reorder'] ?? 0);
    if ($reorderPackageId > 0 && empty($reorderTests)) {
        try {
            $pkgTenantAnd = '';
            $pkgParams = [$reorderPackageId];
            try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenantAnd = ' AND tenant_id = ?'; $pkgParams[] = $tenantId; } catch (Throwable $e) {}
            $pStmt = $db->prepare('SELECT id FROM test_packages WHERE id = ?' . $pkgTenantAnd);
            $pStmt->execute($pkgParams);
            if ($pStmt->fetch()) {
                $st = $db->prepare('SELECT test_id FROM test_package_items WHERE package_id = ?');
                $st->execute([$reorderPackageId]);
                $reorderTests = array_values(array_filter(array_map(fn($r) => (int)$r['test_id'], $st->fetchAll()), fn($v) => $v > 0));
            } else {
                $reorderPackageId = 0;
            }
        } catch (Throwable $e) {}
    }
    if ($reorderId > 0) {
        try {
            $orderTenantAnd = '';
            $orderParams = [$reorderId];
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAnd = ' AND tenant_id = ?'; $orderParams[] = $tenantId; } catch (Throwable $e) {}
            $stmt = $db->prepare('SELECT patient_id, doctor_id, branch_id FROM lab_orders WHERE id = ?' . $orderTenantAnd);
            $stmt->execute($orderParams);
            $o = $stmt->fetch();
            if ($o) {
                $reorderPatientId = (int)$o['patient_id'];
                $reorderDoctorId = (int)($o['doctor_id'] ?? 0);
                $reorderBranchId = (int)($o['branch_id'] ?? 0);
                $stmt = $db->prepare('SELECT test_id FROM order_items WHERE order_id = ?');
                $stmt->execute([$reorderId]);
                $reorderTests = array_values(array_filter(array_map(function($r){ return (int)$r['test_id']; }, $stmt->fetchAll()), fn($v)=>$v>0));
            }
        } catch (Throwable $e) {}
    }

    $packages = [];
    try {
        try {
            $db->query('SELECT tenant_id FROM patients LIMIT 1');
            $stmt = $db->prepare('SELECT id, patient_code, full_name FROM patients WHERE tenant_id = ? ORDER BY id DESC LIMIT 500');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, patient_code, full_name FROM patients ORDER BY id DESC LIMIT 500');
        }
        $patients = $stmt->fetchAll();

        try {
            $db->query('SELECT tenant_id FROM tests LIMIT 1');
            $stmt = $db->prepare('SELECT id, test_code, name, default_price FROM tests WHERE tenant_id = ? ORDER BY name ASC');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, test_code, name, default_price FROM tests ORDER BY name ASC');
        }
        $tests = $stmt->fetchAll();

        try {
            $db->query('SELECT tenant_id FROM doctors LIMIT 1');
            $stmt = $db->prepare('SELECT id, full_name FROM doctors WHERE tenant_id = ? ORDER BY full_name ASC');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, full_name FROM doctors ORDER BY full_name ASC');
        }
        $doctors = $stmt->fetchAll();

        try {
            $db->query('SELECT tenant_id FROM branches LIMIT 1');
            $stmt = $db->prepare('SELECT id, branch_code, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, branch_code, name FROM branches WHERE is_active = 1 ORDER BY name');
        }
        $branches = $stmt->fetchAll();

        try {
            $db->query('SELECT id FROM test_packages LIMIT 1');
            $pkgTenant = '';
            try { $db->query('SELECT tenant_id FROM test_packages LIMIT 1'); $pkgTenant = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $stmt = $db->query('SELECT tp.id, tp.name, tp.price, GROUP_CONCAT(tpi.test_id) AS test_ids FROM test_packages tp LEFT JOIN test_package_items tpi ON tpi.package_id = tp.id WHERE tp.is_active = 1' . $pkgTenant . ' GROUP BY tp.id, tp.name, tp.price ORDER BY tp.name');
            $packages = $stmt->fetchAll();
        } catch (Throwable $e) {}
    } catch (Throwable $e) {
    }

    ?>
    <div class="page-header">
        <h1>إنشاء طلب فحوصات</h1>
    </div>
    <div class="card">
    <?php if (!empty($_SESSION['orders_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['orders_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['orders_error']); ?></div>
    <?php endif; ?>
    <form method="post" class="form-grid">
        <div class="full-width">
            <label>الفرع / المختبر</label>
            <select name="branch_id" required>
                <option value="">اختر الفرع</option>
                <?php 
                $defaultBranch = $reorderBranchId > 0 ? $reorderBranchId : (($auth instanceof Auth) ? $auth->branchId() : 1);
                if ($defaultBranch === null) $defaultBranch = 1;
                foreach ($branches as $br): ?>
                    <option value="<?php echo (int)$br['id']; ?>" <?php echo (int)$br['id'] === $defaultBranch ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($br['name'] . ' (' . $br['branch_code'] . ')', ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="full-width">
            <label>المريض</label>
            <select name="patient_id" required>
                <option value="">اختر المريض</option>
                <?php foreach ($patients as $p): $pid = (int)$p['id']; ?>
                    <option value="<?php echo $pid; ?>" <?php echo $pid === $reorderPatientId ? 'selected' : ''; ?>>
                        <?php
                        echo htmlspecialchars($p['patient_code'], ENT_QUOTES, 'UTF-8')
                            . ' - '
                            . htmlspecialchars($p['full_name'], ENT_QUOTES, 'UTF-8');
                        ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="full-width">
            <label>الطبيب المحوِّل (اختياري)</label>
            <select name="doctor_id">
                <option value="">بدون طبيب</option>
                <?php foreach ($doctors as $d): $did = (int)$d['id']; ?>
                    <option value="<?php echo $did; ?>" <?php echo $did === $reorderDoctorId ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php
        $hasPriorityCol = false;
        try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriorityCol = true; } catch (Throwable $e) {}
        if ($hasPriorityCol): ?>
        <div class="full-width">
            <label>أولوية الطلب</label>
            <select name="priority">
                <option value="normal">عادي</option>
                <option value="high">عالي</option>
                <option value="urgent">عاجل</option>
            </select>
        </div>
        <?php endif; ?>
        <?php if (count($packages) > 0): ?>
        <div class="full-width">
            <label>حزمة فحوصات (اختياري)</label>
            <select name="package_id" id="orderPackageSelect">
                <option value="">— اختر حزمة أو اختر يدوياً أدناه —</option>
                <?php foreach ($packages as $pkg): $pkgId = (int)$pkg['id']; ?>
                <option value="<?php echo $pkgId; ?>" data-tests="<?php echo htmlspecialchars($pkg['test_ids'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" data-price="<?php echo htmlspecialchars($pkg['price'] ?? '0', ENT_QUOTES, 'UTF-8'); ?>" <?php echo $pkgId === $reorderPackageId ? 'selected' : ''; ?>><?php echo htmlspecialchars($pkg['name'], ENT_QUOTES, 'UTF-8'); ?> — <?php echo number_format($pkg['price'] ?? 0); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div class="full-width">
            <label>الفحوصات</label>
            <input type="search" id="orderTestsSearch" placeholder="ابحث بالاسم... (مثل: ALT، سكر، هيموغلوبين)" class="tests-search-input" style="margin-bottom:10px;width:100%;max-width:400px;padding:10px 14px;border:1px solid var(--border);border-radius:var(--radius-sm);font-size:1rem;">
            <div class="tests-list" id="orderTestsList">
                <?php foreach ($tests as $t): $tid = (int)$t['id']; $checked = in_array($tid, $reorderTests); ?>
                    <label class="test-item">
                        <input type="checkbox" name="tests[]" value="<?php echo $tid; ?>" <?php echo $checked ? 'checked' : ''; ?>>
                        <?php
                        echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8');
                        echo ' (' . htmlspecialchars($t['default_price'], ENT_QUOTES, 'UTF-8') . ')';
                        ?>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="full-width form-actions">
            <button type="submit">حفظ الطلب</button>
            <a href="index.php?page=orders" class="btn-secondary">رجوع</a>
        </div>
    </form>
    </div>
    <script>
    (function(){
        var list = document.getElementById('orderTestsList');
        var searchInput = document.getElementById('orderTestsSearch');
        if (list && searchInput) {
            searchInput.addEventListener('input', function(){
                var q = (this.value || '').trim().toLowerCase();
                list.querySelectorAll('.test-item').forEach(function(label){
                    var text = (label.textContent || '').toLowerCase();
                    label.style.display = q === '' || text.indexOf(q) >= 0 ? '' : 'none';
                });
            });
        }
        <?php if (count($packages) > 0): ?>
        var sel = document.getElementById('orderPackageSelect');
        if (sel && list) {
            sel.onchange = function(){
                var opt = this.options[this.selectedIndex];
                var tests = (opt.getAttribute('data-tests') || '').split(',').filter(Boolean);
                list.querySelectorAll('input[type=checkbox]').forEach(function(cb){
                    cb.checked = tests.indexOf(cb.value) >= 0;
                });
            };
        }
        <?php endif; ?>
    })();
    </script>
    <?php
    return;
}

// عرض تفاصيل الطلب
if ($action === 'view' && isset($_GET['id'])) {
    $orderId = (int)$_GET['id'];
    
    try {
        $stmt = $db->prepare(
            'SELECT o.*, p.full_name AS patient_name, p.patient_code, p.phone AS patient_phone, p.email AS patient_email,
                    d.full_name AS doctor_name, d.phone AS doctor_phone,
                    b.name AS branch_name, b.branch_code,
                    u.full_name AS created_by_name
             FROM lab_orders o
             JOIN patients p ON p.id = o.patient_id
             LEFT JOIN doctors d ON d.id = o.doctor_id
             LEFT JOIN branches b ON b.id = o.branch_id
             LEFT JOIN users u ON u.id = o.created_by
             WHERE o.id = ? AND o.tenant_id = ?'
        );
        $stmt->execute([$orderId, $tenantId]);
        $order = $stmt->fetch();
        
        if (!$order) {
            header('Location: index.php?page=orders');
            exit;
        }
        
        // عناصر الطلب
        $stmt = $db->prepare(
            'SELECT oi.*, t.name AS test_name, t.test_code, s.sample_code, s.barcode
             FROM order_items oi
             JOIN tests t ON t.id = oi.test_id
             LEFT JOIN samples s ON s.id = oi.sample_id
             WHERE oi.order_id = ?
             ORDER BY oi.id'
        );
        $stmt->execute([$orderId]);
        $orderItems = $stmt->fetchAll();
        
        // إحصائيات الطلب
        $orderStats = [
            'total_items' => count($orderItems),
            'completed_items' => count(array_filter($orderItems, fn($i) => $i['status'] === 'completed')),
            'pending_items' => count(array_filter($orderItems, fn($i) => $i['status'] === 'pending'))
        ];
    } catch (Throwable $e) {
        header('Location: index.php?page=orders');
        exit;
    }
    
    $statusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغى'];
    $payLabels = ['unpaid' => 'غير مدفوع', 'partial' => 'مدفوع جزئياً', 'paid' => 'مدفوع'];
    ?>
    <div class="page-header">
        <h1>تفاصيل الطلب #<?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <div class="actions-bar">
            <a href="index.php?page=results&order_id=<?php echo $orderId; ?>" class="btn-primary">📊 النتائج</a>
            <a href="index.php?page=orders&action=create&reorder=<?php echo $orderId; ?>" class="btn-secondary">🔄 إعادة طلب</a>
            <?php if ($order['payment_status'] !== 'paid'): ?>
            <a href="index.php?page=billing&action=create&order_id=<?php echo $orderId; ?>" class="btn-secondary">💰 فاتورة</a>
            <?php endif; ?>
            <a href="index.php?page=orders" class="btn-secondary">رجوع</a>
        </div>
    </div>
    
    <?php if (!empty($_SESSION['orders_msg'])): ?>
    <div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['orders_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['orders_msg']); ?></div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['orders_error'])): ?>
    <div class="alert alert-danger" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['orders_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['orders_error']); ?></div>
    <?php endif; ?>
    
    <!-- إحصائيات -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo number_format($orderStats['total_items']); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الفحوصات</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo number_format($orderStats['completed_items']); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">مكتملة</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo number_format($orderStats['pending_items']); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">قيد الانتظار</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo number_format((float)$order['net_amount'], 2); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">المبلغ الإجمالي</div>
        </div>
    </div>
    
    <!-- معلومات الطلب -->
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">معلومات الطلب</h3>
        <div class="form-grid">
            <div>
                <label>رقم الطلب</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><code><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></code></div>
            </div>
            <div>
                <label>التاريخ</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo date('Y-m-d H:i', strtotime($order['order_date'])); ?></div>
            </div>
            <div>
                <label>الحالة</label>
                <div style="padding:8px;">
                    <span class="badge badge-<?php echo $order['status'] === 'completed' ? 'completed' : ($order['status'] === 'cancelled' ? 'cancelled' : ($order['status'] === 'in_progress' ? 'in-progress' : 'pending')); ?>">
                        <?php echo htmlspecialchars($statusLabels[$order['status']] ?? $order['status'], ENT_QUOTES, 'UTF-8'); ?>
                    </span>
                </div>
            </div>
            <div>
                <label>حالة الدفع</label>
                <div style="padding:8px;">
                    <span class="badge badge-<?php echo $order['payment_status'] === 'paid' ? 'completed' : ($order['payment_status'] === 'partial' ? 'in-progress' : 'cancelled'); ?>">
                        <?php echo htmlspecialchars($payLabels[$order['payment_status']] ?? $order['payment_status'], ENT_QUOTES, 'UTF-8'); ?>
                    </span>
                </div>
            </div>
            <?php if (!empty($order['priority'])): ?>
            <div>
                <label>الأولوية</label>
                <div style="padding:8px;">
                    <span style="padding:4px 8px;border-radius:4px;font-size:0.9em;background:<?php echo $order['priority'] === 'urgent' ? '#dc2626' : ($order['priority'] === 'high' ? '#f59e0b' : '#6b7280'); ?>;color:white;">
                        <?php echo $order['priority'] === 'urgent' ? 'عاجل' : ($order['priority'] === 'high' ? 'عالي' : 'عادي'); ?>
                    </span>
                </div>
            </div>
            <?php endif; ?>
            <div>
                <label>الفرع</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['branch_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>أنشئ بواسطة</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['created_by_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
        </div>
    </div>
    
    <!-- معلومات المريض -->
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">معلومات المريض</h3>
        <div class="form-grid">
            <div>
                <label>الاسم</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>كود المريض</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><code><?php echo htmlspecialchars($order['patient_code'], ENT_QUOTES, 'UTF-8'); ?></code></div>
            </div>
            <div>
                <label>الهاتف</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['patient_phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>البريد</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['patient_email'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
        </div>
    </div>
    
    <?php if ($order['doctor_name']): ?>
    <!-- معلومات الطبيب -->
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">معلومات الطبيب</h3>
        <div class="form-grid">
            <div>
                <label>الاسم</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['doctor_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label>الهاتف</label>
                <div style="padding:8px;background:var(--bg-secondary);border-radius:4px;"><?php echo htmlspecialchars($order['doctor_phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- الفحوصات -->
    <div class="card" style="margin-bottom:16px;">
        <h3 style="margin-top:0;">الفحوصات</h3>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>اسم الفحص</th>
                        <th>كود الفحص</th>
                        <th>كود العينة</th>
                        <th>السعر</th>
                        <th>الحالة</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orderItems as $idx => $item): ?>
                    <tr>
                        <td><?php echo $idx + 1; ?></td>
                        <td><?php echo htmlspecialchars($item['test_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><code><?php echo htmlspecialchars($item['test_code'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></code></td>
                        <td><code><?php echo htmlspecialchars($item['sample_code'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></code></td>
                        <td><?php echo number_format((float)$item['price'], 2); ?></td>
                        <td>
                            <span class="badge badge-<?php echo $item['status'] === 'completed' ? 'completed' : 'pending'; ?>">
                                <?php echo $item['status'] === 'completed' ? 'مكتمل' : 'قيد الانتظار'; ?>
                            </span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- تحديث الحالة -->
    <?php if ($order['status'] !== 'cancelled'): ?>
    <div class="card">
        <h3 style="margin-top:0;">تحديث حالة الطلب</h3>
        <form method="post" action="index.php?page=orders&action=update_status" style="max-width:400px;">
            <input type="hidden" name="order_id" value="<?php echo $orderId; ?>">
            <div style="margin-bottom:12px;">
                <label>الحالة الجديدة</label>
                <select name="status" required>
                    <option value="new" <?php echo $order['status'] === 'new' ? 'selected' : ''; ?>>جديد</option>
                    <option value="in_progress" <?php echo $order['status'] === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
                    <option value="completed" <?php echo $order['status'] === 'completed' ? 'selected' : ''; ?>>مكتمل</option>
                </select>
            </div>
            <?php
            $hasPriorityCol = false;
            try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriorityCol = true; } catch (Throwable $e) {}
            if ($hasPriorityCol): ?>
            <div style="margin-bottom:12px;">
                <label>الأولوية</label>
                <select name="priority">
                    <option value="normal" <?php echo ($order['priority'] ?? '') === 'normal' ? 'selected' : ''; ?>>عادي</option>
                    <option value="high" <?php echo ($order['priority'] ?? '') === 'high' ? 'selected' : ''; ?>>عالي</option>
                    <option value="urgent" <?php echo ($order['priority'] ?? '') === 'urgent' ? 'selected' : ''; ?>>عاجل</option>
                </select>
            </div>
            <?php endif; ?>
            <div>
                <button type="submit" class="btn-primary">تحديث</button>
            </div>
        </form>
    </div>
    <?php endif; ?>
    
    <?php
    return;
}

// قائمة الطلبات
$orders = [];
$branchFilter = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
$orderSearch = trim($_GET['q'] ?? '');
$doctorFilter = isset($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;
$statusFilter = $_GET['status'] ?? '';
$paymentFilter = $_GET['payment'] ?? '';
$priorityFilter = $_GET['priority'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';
$exportOrdersCsv = isset($_GET['export']) && $_GET['export'] === 'csv';
$orderPage = max(1, (int)($_GET['p'] ?? 1));
$ordersPerPage = 25;
$orderOffset = ($orderPage - 1) * $ordersPerPage;
$userBranchId = ($auth instanceof Auth) ? $auth->branchId() : null;
if ($userBranchId !== null && $branchFilter === 0) {
    $branchFilter = $userBranchId;
}

// إحصائيات الطلبات
$orderStats = [];
try {
    $tenantAnd = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantAnd = ' WHERE tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    
    $stmt = $db->query('SELECT COUNT(*) FROM lab_orders' . $tenantAnd);
    $orderStats['total'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders' . $tenantAnd . ' AND DATE(created_at) = CURDATE()');
    $stmt->execute();
    $orderStats['today'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders' . $tenantAnd . ' AND status = ?');
    $stmt->execute(['completed']);
    $orderStats['completed'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders' . $tenantAnd . ' AND status IN (?, ?)');
    $stmt->execute(['new', 'in_progress']);
    $orderStats['pending'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COALESCE(SUM(net_amount), 0) FROM lab_orders' . $tenantAnd);
    $stmt->execute();
    $orderStats['total_revenue'] = (float)$stmt->fetchColumn();
} catch (Throwable $e) {
    $orderStats = ['total' => 0, 'today' => 0, 'completed' => 0, 'pending' => 0, 'total_revenue' => 0];
}

try {
    $hasPriorityCol = false;
    try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriorityCol = true; } catch (Throwable $e) {}
    $prioritySel = $hasPriorityCol ? ', o.priority' : '';
    $sql = 'SELECT o.id, o.order_number, o.order_date, o.status' . $prioritySel . ', o.net_amount, o.payment_status, o.created_at,
                p.full_name AS patient_name,
                d.full_name AS doctor_name,
                b.name AS branch_name
         FROM lab_orders o
         JOIN patients p ON p.id = o.patient_id
         LEFT JOIN doctors d ON d.id = o.doctor_id
         LEFT JOIN branches b ON b.id = o.branch_id
         WHERE o.tenant_id = :tid';
    $params = ['tid' => $tenantId];
    
    if ($branchFilter > 0) {
        $sql .= ' AND o.branch_id = :branch_id';
        $params['branch_id'] = $branchFilter;
    }
    if ($doctorFilter > 0) {
        $sql .= ' AND o.doctor_id = :doctor_id';
        $params['doctor_id'] = $doctorFilter;
    }
    if ($statusFilter !== '') {
        $sql .= ' AND o.status = :status';
        $params['status'] = $statusFilter;
    }
    if ($paymentFilter !== '') {
        $sql .= ' AND o.payment_status = :payment';
        $params['payment'] = $paymentFilter;
    }
    if ($dateFrom !== '') {
        $sql .= ' AND DATE(o.order_date) >= :date_from';
        $params['date_from'] = $dateFrom;
    }
    if ($dateTo !== '') {
        $sql .= ' AND DATE(o.order_date) <= :date_to';
        $params['date_to'] = $dateTo;
    }
    if ($orderSearch !== '') {
        $sql .= ' AND (o.order_number LIKE :q OR p.full_name LIKE :q2)';
        $params['q'] = '%' . $orderSearch . '%';
        $params['q2'] = '%' . $orderSearch . '%';
    }
    if ($hasPriorityCol && $priorityFilter !== '') {
        $sql .= ' AND o.priority = :priority';
        $params['priority'] = $priorityFilter;
    }
    
    $cntSql = 'SELECT COUNT(*) FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE o.tenant_id = :tid';
    $cntParams = ['tid' => $tenantId];
    if ($branchFilter > 0) {
        $cntSql .= ' AND o.branch_id = :branch_id';
        $cntParams['branch_id'] = $branchFilter;
    }
    if ($doctorFilter > 0) {
        $cntSql .= ' AND o.doctor_id = :doctor_id';
        $cntParams['doctor_id'] = $doctorFilter;
    }
    if ($statusFilter !== '') {
        $cntSql .= ' AND o.status = :status';
        $cntParams['status'] = $statusFilter;
    }
    if ($paymentFilter !== '') {
        $cntSql .= ' AND o.payment_status = :payment';
        $cntParams['payment'] = $paymentFilter;
    }
    if ($hasPriorityCol && $priorityFilter !== '') {
        $cntSql .= ' AND o.priority = :priority';
        $cntParams['priority'] = $priorityFilter;
    }
    if ($dateFrom !== '') {
        $cntSql .= ' AND DATE(o.order_date) >= :date_from';
        $cntParams['date_from'] = $dateFrom;
    }
    if ($dateTo !== '') {
        $cntSql .= ' AND DATE(o.order_date) <= :date_to';
        $cntParams['date_to'] = $dateTo;
    }
    if ($orderSearch !== '') {
        $cntSql .= ' AND (o.order_number LIKE :q OR p.full_name LIKE :q2)';
        $cntParams['q'] = '%' . $orderSearch . '%';
        $cntParams['q2'] = '%' . $orderSearch . '%';
    }
    
    $cntStmt = $db->prepare($cntSql);
    $cntStmt->execute($cntParams);
    $totalOrdersCount = (int)$cntStmt->fetchColumn();
    
    $sql .= ' ORDER BY o.id DESC LIMIT ' . (int)$ordersPerPage . ' OFFSET ' . (int)$orderOffset;
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll();
} catch (Throwable $e) {
    $totalOrdersCount = 0;
    $orders = [];
}
$totalOrdersPages = $totalOrdersCount > 0 ? (int)ceil($totalOrdersCount / $ordersPerPage) : 1;

if ($exportOrdersCsv) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="orders_' . date('Y-m-d') . '.csv"');
    echo "\xEF\xBB\xBF";
    $csvHeader = "رقم الطلب,التاريخ,المريض,الطبيب,الفرع,الحالة," . ($hasPriorityCol ? "الأولوية," : "") . "الدفع,المبلغ\n";
    echo $csvHeader;
    foreach ($orders as $r) {
        $line = [
            $r['order_number'], 
            $r['order_date'], 
            $r['patient_name'], 
            $r['doctor_name'] ?? '', 
            $r['branch_name'] ?? '',
            $r['status']
        ];
        if ($hasPriorityCol) $line[] = ($r['priority'] ?? '') === 'urgent' ? 'عاجل' : (($r['priority'] ?? '') === 'high' ? 'عالي' : 'عادي');
        $line[] = $r['payment_status'];
        $line[] = $r['net_amount'] ?? '';
        $esc = array_map(fn($v) => strpbrk((string)$v, ",\"\n\r") !== false ? '"'.str_replace('"','""',(string)$v).'"' : (string)$v, $line);
        echo implode(',', $esc) . "\n";
    }
    exit;
}

$branchesForFilter = [];
try {
    try {
        $db->query('SELECT tenant_id FROM branches LIMIT 1');
        $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
        $stmt->execute([$tenantId]);
    } catch (Throwable $e) {
        $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
    }
    $branchesForFilter = $stmt->fetchAll();
} catch (Throwable $e) {}
$statusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغى'];
$payLabels = ['unpaid' => 'غير مدفوع', 'partial' => 'مدفوع جزئياً', 'paid' => 'مدفوع'];
?>
<div class="page-header">
    <h1>📋 طلبات الفحوصات</h1>
    <div class="actions-bar">
        <a href="index.php?page=orders&action=create" class="btn-primary">➕ طلب جديد</a>
    </div>
</div>

<?php if (!empty($_SESSION['orders_msg'])): ?>
<div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['orders_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['orders_msg']); ?></div>
<?php endif; ?>
<?php if (!empty($_SESSION['orders_error'])): ?>
<div class="alert alert-danger" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['orders_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['orders_error']); ?></div>
<?php endif; ?>

<!-- إحصائيات -->
<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--primary);"><?php echo number_format($orderStats['total']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إجمالي الطلبات</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo number_format($orderStats['today']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">طلبات اليوم</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--info);"><?php echo number_format($orderStats['completed']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">مكتملة</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo number_format($orderStats['pending']); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">قيد الانتظار</div>
    </div>
    <div class="card" style="text-align:center;">
        <div style="font-size:2rem;font-weight:bold;color:var(--success);"><?php echo number_format($orderStats['total_revenue'], 2); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إجمالي الإيرادات</div>
    </div>
</div>

<!-- الفلترة -->
<div class="card" style="margin-bottom:16px;">
    <form method="get" action="index.php" style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:12px;align-items:end;">
        <input type="hidden" name="page" value="orders">
        <div>
            <label>بحث</label>
            <input type="search" name="q" placeholder="رقم طلب أو مريض..." value="<?php echo htmlspecialchars($orderSearch, ENT_QUOTES, 'UTF-8'); ?>">
        </div>
        <?php if ($userBranchId === null): ?>
        <div>
            <label>الفرع</label>
            <select name="branch_id">
                <option value="">الكل</option>
                <?php foreach ($branchesForFilter as $br): ?>
                    <option value="<?php echo (int)$br['id']; ?>" <?php echo $branchFilter === (int)$br['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div>
            <label>الحالة</label>
            <select name="status">
                <option value="">الكل</option>
                <option value="new" <?php echo $statusFilter === 'new' ? 'selected' : ''; ?>>جديد</option>
                <option value="in_progress" <?php echo $statusFilter === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
                <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>مكتمل</option>
                <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>ملغى</option>
            </select>
        </div>
        <div>
            <label>حالة الدفع</label>
            <select name="payment">
                <option value="">الكل</option>
                <option value="unpaid" <?php echo $paymentFilter === 'unpaid' ? 'selected' : ''; ?>>غير مدفوع</option>
                <option value="partial" <?php echo $paymentFilter === 'partial' ? 'selected' : ''; ?>>مدفوع جزئياً</option>
                <option value="paid" <?php echo $paymentFilter === 'paid' ? 'selected' : ''; ?>>مدفوع</option>
            </select>
        </div>
        <?php
        $hasPriorityFilter = false;
        try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriorityFilter = true; } catch (Throwable $e) {}
        if ($hasPriorityFilter): ?>
        <div>
            <label>الأولوية</label>
            <select name="priority">
                <option value="">الكل</option>
                <option value="normal" <?php echo $priorityFilter === 'normal' ? 'selected' : ''; ?>>عادي</option>
                <option value="high" <?php echo $priorityFilter === 'high' ? 'selected' : ''; ?>>عالي</option>
                <option value="urgent" <?php echo $priorityFilter === 'urgent' ? 'selected' : ''; ?>>عاجل</option>
            </select>
        </div>
        <?php endif; ?>
        <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 ($orderSearch || $branchFilter || $statusFilter || $paymentFilter || $dateFrom || $dateTo): ?>
                <a href="index.php?page=orders" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </div>
    </form>
    <div style="margin-top:12px;">
        <a href="index.php?page=orders&export=csv<?php 
            $exportParams = [];
            if ($branchFilter) $exportParams[] = 'branch_id=' . $branchFilter;
            if ($statusFilter) $exportParams[] = 'status=' . urlencode($statusFilter);
            if ($paymentFilter) $exportParams[] = 'payment=' . urlencode($paymentFilter);
            if ($priorityFilter) $exportParams[] = 'priority=' . urlencode($priorityFilter);
            if ($dateFrom) $exportParams[] = 'date_from=' . urlencode($dateFrom);
            if ($dateTo) $exportParams[] = 'date_to=' . urlencode($dateTo);
            echo !empty($exportParams) ? '&' . implode('&', $exportParams) : '';
        ?>" class="btn-secondary">📥 تصدير CSV</a>
    </div>
</div>

<!-- الجدول -->
<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>الإجراءات</th>
        </tr>
    </thead>
    <tbody>
    <?php if (empty($orders)): ?>
        <tr><td colspan="<?php echo 9 + ($hasPriorityCol ? 1 : 0); ?>" style="text-align:center;padding:24px;color:var(--text-muted);">لا توجد نتائج</td></tr>
    <?php else: ?>
    <?php foreach ($orders as $o): ?>
        <tr>
            <td><strong><code><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></code></strong></td>
            <td><?php echo htmlspecialchars($o['branch_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($o['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($o['doctor_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <div style="font-size:0.85rem;"><?php echo date('Y-m-d', strtotime($o['order_date'])); ?></div>
                <div style="font-size:0.75rem;color:var(--text-muted);"><?php echo date('H:i', strtotime($o['order_date'])); ?></div>
            </td>
            <td>
                <span class="badge badge-<?php echo $o['status'] === 'completed' ? 'completed' : ($o['status'] === 'cancelled' ? 'cancelled' : ($o['status'] === 'in_progress' ? 'in-progress' : 'pending')); ?>">
                    <?php echo htmlspecialchars($statusLabels[$o['status']] ?? $o['status'], ENT_QUOTES, 'UTF-8'); ?>
                </span>
            </td>
            <td>
                <span class="badge badge-<?php echo $o['payment_status'] === 'paid' ? 'completed' : ($o['payment_status'] === 'partial' ? 'in-progress' : 'cancelled'); ?>">
                    <?php echo htmlspecialchars($payLabels[$o['payment_status']] ?? $o['payment_status'], ENT_QUOTES, 'UTF-8'); ?>
                </span>
            </td>
            <td><strong><?php echo number_format((float)$o['net_amount'], 2); ?></strong></td>
            <td>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="index.php?page=orders&action=view&id=<?php echo (int)$o['id']; ?>" class="btn-link">👁️ عرض</a>
                    <a href="index.php?page=results&order_id=<?php echo (int)$o['id']; ?>" class="btn-link">📊 نتائج</a>
                    <a href="index.php?page=orders&action=create&reorder=<?php echo (int)$o['id']; ?>" class="btn-link">🔄 إعادة</a>
                    <?php if ($o['payment_status'] !== 'paid'): ?>
                    <a href="index.php?page=billing&action=create&order_id=<?php echo (int)$o['id']; ?>" class="btn-link">💰 فاتورة</a>
                    <?php endif; ?>
                    <?php if ($o['status'] !== 'cancelled'): ?>
                    <a href="index.php?page=orders&action=cancel&id=<?php echo (int)$o['id']; ?>" 
                       class="btn-link" 
                       style="color:var(--danger);"
                       onclick="return confirm('هل أنت متأكد من إلغاء هذا الطلب؟');">❌ إلغاء</a>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
</table>
</div>

<?php if ($totalOrdersPages > 1): ?>
<?php 
$navParams = ['page'=>'orders','p'=>1]; 
if ($branchFilter>0) $navParams['branch_id']=$branchFilter; 
if ($doctorFilter>0) $navParams['doctor_id']=$doctorFilter; 
if ($orderSearch!=='') $navParams['q']=$orderSearch;
if ($statusFilter !== '') $navParams['status'] = $statusFilter;
if ($paymentFilter !== '') $navParams['payment'] = $paymentFilter;
if ($priorityFilter !== '') $navParams['priority'] = $priorityFilter;
if ($dateFrom !== '') $navParams['date_from'] = $dateFrom;
if ($dateTo !== '') $navParams['date_to'] = $dateTo;
?>
<div class="pagination" style="margin-top:16px;">
    <?php for ($i = 1; $i <= min($totalOrdersPages, 10); $i++): $navParams['p']=$i; ?>
        <a href="index.php?<?php echo http_build_query($navParams); ?>" <?php echo $i === $orderPage ? 'style="font-weight:bold;"' : ''; ?>><?php echo $i; ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>
