<?php

use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('integration.manage')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى تكامل الأجهزة';
    return;
}

$devices = [];
$deviceTests = [];
$tests = [];
$tenantId = (int)Tenant::id();
$tenantTestAnd = '';
try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $tenantTestAnd = ' AND t.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
$tenantTestWhere = '';
try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $tenantTestWhere = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['create_device'])) {
        $name = trim($_POST['name'] ?? '');
        $vendor = trim($_POST['vendor'] ?? '');
        $model = trim($_POST['model'] ?? '');
        $serial = trim($_POST['serial_number'] ?? '');
        $connectionType = trim($_POST['connection_type'] ?? '');
        $location = trim($_POST['location'] ?? '');

        if ($name !== '') {
            try {
                $cols = 'name, vendor, model, serial_number, connection_type, location';
                $vals = ':name, :vendor, :model, :serial, :ctype, :loc';
                $params = ['name' => $name, 'vendor' => $vendor !== '' ? $vendor : null, 'model' => $model !== '' ? $model : null, 'serial' => $serial !== '' ? $serial : null, 'ctype' => $connectionType !== '' ? $connectionType : null, 'loc' => $location !== '' ? $location : null];
                $db->query('SELECT tenant_id FROM devices LIMIT 1');
                $cols .= ', tenant_id';
                $vals .= ', :tid';
                $params['tid'] = $tenantId;
                $stmt = $db->prepare("INSERT INTO devices ($cols) VALUES ($vals)");
                $stmt->execute($params);
            } catch (Throwable $e) {
                $stmt = $db->prepare('INSERT INTO devices (name, vendor, model, serial_number, connection_type, location) VALUES (:name, :vendor, :model, :serial, :ctype, :loc)');
                $stmt->execute(['name' => $name, 'vendor' => $vendor !== '' ? $vendor : null, 'model' => $model !== '' ? $model : null, 'serial' => $serial !== '' ? $serial : null, 'ctype' => $connectionType !== '' ? $connectionType : null, 'loc' => $location !== '' ? $location : null]);
            }
        }
    } elseif (isset($_POST['map_test'])) {
        $deviceId = (int)($_POST['device_id'] ?? 0);
        $testId = (int)($_POST['test_id'] ?? 0);
        $code = trim($_POST['device_test_code'] ?? '');

        if ($deviceId > 0 && $testId > 0 && $code !== '') {
            try {
                $stmt = $db->prepare('INSERT INTO device_tests (device_id, test_id, device_test_code, tenant_id) VALUES (:device_id, :test_id, :code, :tid)');
                $stmt->execute(['device_id' => $deviceId, 'test_id' => $testId, 'code' => $code, 'tid' => $tenantId]);
            } catch (Throwable $e) {
                $stmt = $db->prepare('INSERT INTO device_tests (device_id, test_id, device_test_code) VALUES (:device_id, :test_id, :code)');
                $stmt->execute(['device_id' => $deviceId, 'test_id' => $testId, 'code' => $code]);
            }
        }
    } elseif (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $csv = $_FILES['csv_file']['tmp_name'];
        $rows = array_map('str_getcsv', file($csv));
        $imported = 0;
        $deviceId = (int)($_POST['csv_device_id'] ?? 0);
        foreach ($rows as $i => $row) {
            if ($i === 0 && preg_match('/order|رقم|number/i', $row[0] ?? '')) continue;
            $orderNum = trim($row[0] ?? '');
            $testCode = trim($row[1] ?? '');
            $value = trim($row[2] ?? '');
            if ($orderNum === '' || $value === '') continue;
            try {
                if ($deviceId > 0) {
                    $stmt = $db->prepare('SELECT dt.test_id FROM device_tests dt WHERE dt.device_id = ? AND dt.device_test_code = ?');
                    $stmt->execute([$deviceId, $testCode]);
                    $t = $stmt->fetch();
                    $testId = $t ? (int)$t['test_id'] : null;
                } else {
                    $stmt = $db->prepare('SELECT id FROM tests WHERE test_code = ?' . $tenantTestWhere);
                    $stmt->execute([$testCode]);
                    $t = $stmt->fetch();
                    $testId = $t ? (int)$t['id'] : null;
                }
                if (!$testId) continue;
                $stmt = $db->prepare('SELECT oi.id FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE o.order_number = ? AND oi.test_id = ?');
                $stmt->execute([$orderNum, $testId]);
                $oi = $stmt->fetch();
                if (!$oi) continue;
                $itemId = (int)$oi['id'];
                $stmt = $db->prepare('SELECT id FROM results WHERE order_item_id = ?');
                $stmt->execute([$itemId]);
                $ex = $stmt->fetch();
                if ($ex) {
                    $db->prepare('UPDATE results SET result_value = ?, result_date = NOW() WHERE order_item_id = ?')->execute([$value, $itemId]);
                } else {
                    $db->prepare('INSERT INTO results (order_item_id, result_value, result_date) VALUES (?, ?, NOW())')->execute([$itemId, $value]);
                }
                $db->prepare("UPDATE order_items SET status = 'validated' WHERE id = ?")->execute([$itemId]);
                $imported++;
            } catch (Throwable $e) {}
        }
        $_SESSION['csv_imported'] = $imported;
        header('Location: index.php?page=integration&csv=1');
        exit;
    }
}

if (isset($_GET['csv']) && isset($_SESSION['csv_imported'])) {
    $csvImported = (int)$_SESSION['csv_imported'];
    unset($_SESSION['csv_imported']);
}

$devices = [];
$tests = [];
$deviceTests = [];
$devicesWhere = '';
try {
    $db->query('SELECT tenant_id FROM devices LIMIT 1');
    $devicesWhere = ' WHERE tenant_id = ' . (int)$tenantId;
} catch (Throwable $e) {}
try {
    $stmt = $devicesWhere ? $db->prepare('SELECT id, name, vendor, model, connection_type, location, is_active, created_at FROM devices' . $devicesWhere . ' ORDER BY id DESC LIMIT 50') : $db->query('SELECT id, name, vendor, model, connection_type, location, is_active, created_at FROM devices ORDER BY id DESC LIMIT 50');
    if ($devicesWhere) $stmt->execute();
    $devices = $stmt->fetchAll();
} catch (Throwable $e) {}
try {
    $stmt = $db->query('SELECT id, name, test_code FROM tests WHERE 1=1' . $tenantTestWhere . ' ORDER BY name LIMIT 200');
    $tests = $stmt->fetchAll();
} catch (Throwable $e) {}
$deviceTestsAnd = $tenantTestAnd;
try {
    $db->query('SELECT tenant_id FROM device_tests LIMIT 1');
    $deviceTestsAnd .= ' AND d.tenant_id = ' . (int)$tenantId;
} catch (Throwable $e) {}
try {
    $stmt = $db->query('SELECT dt.id, dt.device_test_code, d.name AS device_name, t.name AS test_name, t.test_code FROM device_tests dt JOIN devices d ON d.id = dt.device_id JOIN tests t ON t.id = dt.test_id' . $deviceTestsAnd . ' ORDER BY dt.id DESC LIMIT 100');
    $deviceTests = $stmt->fetchAll();
} catch (Throwable $e) {
    try {
        $stmt = $db->query('SELECT dt.id, dt.device_test_code, d.name AS device_name, t.name AS test_name, t.test_code FROM device_tests dt JOIN devices d ON d.id = dt.device_id JOIN tests t ON t.id = dt.test_id' . $tenantTestAnd . ' ORDER BY dt.id DESC LIMIT 100');
        $deviceTests = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}
?>
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>تكامل الأجهزة</h1>
        <a href="index.php?page=dashboard" class="btn-secondary">الرئيسية</a>
    </div>
    <p class="page-header-desc">تعريف الأجهزة وربط أكواد الفحوصات بكود الجهاز، واستيراد نتائج من CSV مرتبطة بالطلبات. يكمّل ذلك صفحة «استيراد النتائج» للدفعات العامة.</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <?php if ($auth->can('results.edit') || $auth->can('results.validate')): ?><a href="index.php?page=import_results">استيراد نتائج (CSV عام)</a><?php endif; ?>
        <?php if ($auth->can('integration.manage')): ?><a href="index.php?page=clinic_api">API العيادات</a><?php endif; ?>
        <?php if ($auth->can('quality.manage')): ?><a href="index.php?page=quality">ضبط الجودة</a><?php endif; ?>
    </nav>
</div>
<?php if (isset($csvImported)): ?><div class="alert alert-success">تم استيراد <?php echo (int)$csvImported; ?> نتيجة بنجاح.</div><?php endif; ?>
<div class="section-card">
    <h3>استيراد نتائج من ملف CSV</h3>
    <p>صيغة الملف: رقم_الطلب, كود_الفحص, النتيجة (أو كود الجهاز إذا اخترت جهازاً)</p>
    <form method="post" enctype="multipart/form-data" class="form-grid">
        <div>
            <label>ملف CSV</label>
            <input type="file" name="csv_file" accept=".csv" required>
        </div>
        <div>
            <label>الجهاز (اختياري - لربط بكود الجهاز)</label>
            <select name="csv_device_id">
                <option value="0">-- استخدام كود الفحص مباشرة --</option>
                <?php foreach ($devices as $d): ?><option value="<?php echo (int)$d['id']; ?>"><?php echo htmlspecialchars($d['name'], ENT_QUOTES, 'UTF-8'); ?></option><?php endforeach; ?>
            </select>
        </div>
        <div class="form-actions"><button type="submit">استيراد</button></div>
    </form>
</div>
<div class="section-card">
    <h3>تعريف أجهزة التحاليل</h3>
    <form method="post" class="form-grid">
        <div>
            <label>اسم الجهاز</label>
            <input type="text" name="name" required>
        </div>
        <div>
            <label>الشركة المصنعة</label>
            <input type="text" name="vendor">
        </div>
        <div>
            <label>الموديل</label>
            <input type="text" name="model">
        </div>
        <div>
            <label>الرقم التسلسلي</label>
            <input type="text" name="serial_number">
        </div>
        <div>
            <label>نوع الاتصال</label>
            <input type="text" name="connection_type" placeholder="ASTM, HL7, File, Serial">
        </div>
        <div>
            <label>الموقع</label>
            <input type="text" name="location">
        </div>
        <div class="full-width form-actions">
            <button type="submit" name="create_device" value="1">حفظ الجهاز</button>
        </div>
    </form>
    <div class="table-wrapper" style="margin-top:20px;">
        <table class="table">
            <thead>
                <tr>
                    <th>اسم الجهاز</th>
                    <th>الشركة</th>
                    <th>الموديل</th>
                    <th>نوع الاتصال</th>
                    <th>الموقع</th>
                    <th>تاريخ الإضافة</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($devices as $d): ?>
                <tr>
                    <td><?php echo htmlspecialchars($d['name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['vendor'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['model'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['connection_type'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['location'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['created_at'], ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="section-card">
    <h3>ربط فحوصات النظام بأكواد الجهاز</h3>
    <form method="post" class="form-grid">
        <div>
            <label>الجهاز</label>
            <select name="device_id" required>
                <option value="">اختر الجهاز</option>
                <?php foreach ($devices as $d): ?>
                    <option value="<?php echo (int)$d['id']; ?>">
                        <?php echo htmlspecialchars($d['name'], ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>فحص المختبر</label>
            <select name="test_id" required>
                <option value="">اختر الفحص</option>
                <?php foreach ($tests as $t): ?>
                    <option value="<?php echo (int)$t['id']; ?>">
                        <?php echo htmlspecialchars($t['name'] . ' (' . $t['test_code'] . ')', ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>كود الفحص في الجهاز</label>
            <input type="text" name="device_test_code" required>
        </div>
        <div class="full-width form-actions">
            <button type="submit" name="map_test" value="1">حفظ الربط</button>
        </div>
    </form>
    <div class="table-wrapper" style="margin-top:20px;">
        <table class="table">
            <thead>
                <tr>
                    <th>الجهاز</th>
                    <th>فحص المختبر</th>
                    <th>كود الجهاز</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($deviceTests as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['device_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['test_name'] . ' (' . $row['test_code'] . ')', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['device_test_code'], ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
