<?php
/**
 * لوحة Super Admin - إدارة المختبرات وحساباتها - نسخة مطورة
 * متاحة فقط لمدير المنصة (tenant 1, role 1)
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = (int)Tenant::id();
$roleId = (int)($_SESSION['role_id'] ?? 0);
$isSuperAdmin = ($tenantId === 1 && $roleId === 1);

if (!($auth instanceof Auth) || !$auth->check() || !$isSuperAdmin) {
    http_response_code(403);
    echo 'غير مسموح - لوحة مدير المنصة فقط';
    return;
}

$action = $_GET['action'] ?? 'index';
$editId = (int)($_GET['id'] ?? 0);

// إنشاء مختبر جديد
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $labName = trim($_POST['lab_name'] ?? '');
    $slug = preg_replace('/[^a-z0-9_-]/', '', strtolower(trim($_POST['slug'] ?? '')));
    $adminName = trim($_POST['admin_name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $planId = (int)($_POST['plan_id'] ?? 1);
    $status = in_array(trim($_POST['status'] ?? 'trial'), ['active', 'trial', 'suspended'], true) ? trim($_POST['status']) : 'trial';
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    $addError = '';
    if (strlen($labName) < 2) $addError = 'أدخل اسم المختبر.';
    elseif (strlen($slug) < 2) $addError = 'الرابط (slug) قصير. مثال: mylab';
    elseif (strlen($adminName) < 2) $addError = 'أدخل اسم المدير.';
    elseif (strlen($username) < 3) $addError = 'اسم المستخدم 3 أحرف على الأقل.';
    elseif (strlen($password) < 6) $addError = 'كلمة المرور 6 أحرف على الأقل.';

    if ($addError) {
        $_SESSION['admin_error'] = $addError;
    } else {
        try {
            $db->beginTransaction();
            $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ?');
            $stmt->execute([$slug]);
            if ($stmt->fetch()) {
                $_SESSION['admin_error'] = 'هذا الرابط (slug) مستخدم. اختر آخر.';
            } else {
                $stmt = $db->prepare('SELECT id FROM users WHERE username = ?');
                $stmt->execute([$username]);
                if ($stmt->fetch()) {
                    $_SESSION['admin_error'] = 'اسم المستخدم مستخدم. اختر آخر.';
                } else {
                    $db->prepare('INSERT INTO tenants (slug, name, plan_id, status) VALUES (?, ?, ?, ?)')->execute([$slug, $labName, $planId, $status]);
                    $newTenantId = (int)$db->lastInsertId();

                    $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                    $stmt->execute(['Administrator']);
                    $role = $stmt->fetch();
                    $roleId = $role ? (int)$role['id'] : 1;
                    if (!$role) {
                        $db->prepare('INSERT INTO roles (name) VALUES (?)')->execute(['Administrator']);
                        $roleId = (int)$db->lastInsertId();
                    }

                    $hash = password_hash($password, PASSWORD_BCRYPT);
                    $db->prepare('INSERT INTO users (full_name, username, password_hash, role_id, tenant_id, is_active, email, phone) VALUES (?, ?, ?, ?, ?, 1, ?, ?)')->execute([
                        $adminName, $username, $hash, $roleId, $newTenantId,
                        $email ?: null, $phone ?: null
                    ]);
                    $db->prepare('INSERT INTO branches (branch_code, name, tenant_id) VALUES (?, ?, ?)')->execute([strtoupper($slug), $labName, $newTenantId]);

                    if (isset($auditLog)) {
                        $auditLog->log('tenant_created', 'tenant', $newTenantId, null, json_encode(['name' => $labName, 'slug' => $slug], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                    }

                    $db->commit();
                    $_SESSION['admin_msg'] = 'تم إنشاء المختبر بنجاح. المدير: ' . $username;
                }
            }
            if ($db->inTransaction()) $db->rollBack();
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['admin_error'] = 'حدث خطأ: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=admin_tenants');
    exit;
}

// تعديل مختبر
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST' && $editId > 0) {
    $labName = trim($_POST['lab_name'] ?? '');
    $slug = preg_replace('/[^a-z0-9_-]/', '', strtolower(trim($_POST['slug'] ?? '')));
    $planId = (int)($_POST['plan_id'] ?? 1);
    $status = in_array(trim($_POST['status'] ?? 'active'), ['active', 'trial', 'suspended'], true) ? trim($_POST['status']) : 'active';
    $primaryColor = trim($_POST['primary_color'] ?? '#0d9488');
    $logoUrl = trim($_POST['logo_url'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    if ($editId === 1) {
        $_SESSION['admin_error'] = 'لا يمكن تعديل المختبر الرئيسي.';
    } elseif (strlen($labName) < 2) {
        $_SESSION['admin_error'] = 'اسم المختبر قصير.';
    } elseif (strlen($slug) < 2) {
        $_SESSION['admin_error'] = 'الرابط (slug) قصير.';
    } else {
        try {
            // التحقق من أن slug غير مستخدم من قبل مختبر آخر
            $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ? AND id != ?');
            $stmt->execute([$slug, $editId]);
            if ($stmt->fetch()) {
                $_SESSION['admin_error'] = 'هذا الرابط (slug) مستخدم من قبل مختبر آخر.';
            } else {
                $db->prepare('UPDATE tenants SET name=?, slug=?, plan_id=?, status=?, primary_color=?, logo_url=?, notes=? WHERE id=?')->execute([
                    $labName, $slug, $planId, $status, $primaryColor, $logoUrl ?: null, $notes ?: null, $editId
                ]);
                
                if (isset($auditLog)) {
                    $auditLog->log('tenant_updated', 'tenant', $editId, null, json_encode(['name' => $labName], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
                
                $_SESSION['admin_msg'] = 'تم تحديث معلومات المختبر بنجاح.';
            }
        } catch (Throwable $e) {
            $_SESSION['admin_error'] = 'حدث خطأ: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=admin_tenants&action=view&id=' . $editId);
    exit;
}

// حذف مختبر
if ($action === 'delete' && $editId > 0 && $editId !== 1) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['confirm'])) {
        try {
            $db->beginTransaction();
            $tid = $editId;
            try { $db->prepare('DELETE FROM results WHERE order_item_id IN (SELECT oi.id FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE o.tenant_id = ?)')->execute([$tid]); } catch (Throwable $e) {}
            try { $db->prepare('DELETE FROM order_items WHERE order_id IN (SELECT id FROM lab_orders WHERE tenant_id = ?)')->execute([$tid]); } catch (Throwable $e) {}
            try { $db->prepare('DELETE FROM samples WHERE order_id IN (SELECT id FROM lab_orders WHERE tenant_id = ?)')->execute([$tid]); } catch (Throwable $e) {}
            try { $db->prepare('DELETE FROM invoices WHERE order_id IN (SELECT id FROM lab_orders WHERE tenant_id = ?)')->execute([$tid]); } catch (Throwable $e) {}
            $tablesWithTenant = [
                'lab_signup_requests', 'service_ratings', 'patient_doctor_bookings', 'doctor_appointments',
                'doctor_follow_up_reminders', 'doctor_favorite_patients', 'doctor_alerts', 'doctor_accounts',
                'lab_orders', 'patient_medical_notes', 'patient_attachments', 'patient_balances', 'patients',
                'doctors', 'users', 'branches', 'settings', 'tests', 'inventory_items'
            ];
            foreach ($tablesWithTenant as $tbl) {
                try {
                    $db->query("SELECT tenant_id FROM $tbl LIMIT 1");
                    $db->prepare("DELETE FROM $tbl WHERE tenant_id = ?")->execute([$tid]);
                } catch (Throwable $e) {}
            }
            $db->prepare('DELETE FROM tenants WHERE id = ?')->execute([$tid]);
            $db->commit();
            $_SESSION['admin_msg'] = 'تم حذف المختبر بنجاح.';
            if (isset($auditLog)) {
                $auditLog->log('tenant_deleted', 'tenant', $tid, json_encode(['id' => $tid], JSON_UNESCAPED_UNICODE), null, $_SESSION['user_id'] ?? null);
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['admin_error'] = 'فشل الحذف: ' . $e->getMessage();
        }
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    header('Location: index.php?page=admin_tenants&action=delete_confirm&id=' . $editId);
    exit;
}

// تأكيد الحذف
if ($action === 'delete_confirm' && $editId > 0 && $editId !== 1) {
    $stmt = $db->prepare('SELECT id, name, slug FROM tenants WHERE id = ?');
    $stmt->execute([$editId]);
    $tenantToDelete = $stmt->fetch();
    if (!$tenantToDelete) {
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    ?>
    <div class="page-header">
        <h1>تأكيد حذف المختبر</h1>
    </div>
    <div class="card" style="max-width:500px;">
        <p style="font-size:1.1rem;">هل أنت متأكد من حذف المختبر <strong><?php echo htmlspecialchars($tenantToDelete['name'], ENT_QUOTES, 'UTF-8'); ?></strong> (<?php echo htmlspecialchars($tenantToDelete['slug'], ENT_QUOTES, 'UTF-8'); ?>)?</p>
        <p style="color:var(--danger);font-weight:600;">⚠️ سيتم حذف جميع البيانات: المرضى، الطلبات، المستخدمين، الفروع، وغيرها. لا يمكن التراجع.</p>
        <div style="display:flex;gap:12px;margin-top:20px;">
            <form method="post" action="index.php?page=admin_tenants&action=delete&id=<?php echo (int)$editId; ?>" style="display:inline;">
                <button type="submit" class="btn-primary" style="background:var(--danger);">نعم، احذف المختبر</button>
            </form>
            <a href="index.php?page=admin_tenants" class="btn-secondary">إلغاء</a>
        </div>
    </div>
    <?php
    return;
}

// تغيير حالة المختبر
if ($action === 'toggle_status' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $newStatus = $_POST['status'] ?? '';
    if (in_array($newStatus, ['active', 'suspended', 'trial'], true) && $editId !== 1) {
        try {
            $db->prepare('UPDATE tenants SET status = ? WHERE id = ?')->execute([$newStatus, $editId]);
            $_SESSION['admin_msg'] = 'تم تحديث الحالة.';
            if (isset($auditLog)) {
                $auditLog->log('tenant_status_changed', 'tenant', $editId, null, json_encode(['status' => $newStatus], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
        } catch (Throwable $e) {
            $_SESSION['admin_error'] = 'فشل التحديث.';
        }
    }
    header('Location: index.php?page=admin_tenants');
    exit;
}

// عرض تفاصيل مختبر
if ($action === 'view') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    
    $stmt = $db->prepare('SELECT t.*, p.name AS plan_name FROM tenants t LEFT JOIN subscription_plans p ON p.id = t.plan_id WHERE t.id = ?');
    $stmt->execute([$id]);
    $tenant = $stmt->fetch();
    
    if (!$tenant) {
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    
    // إحصائيات مفصلة
    $stats = [];
    $stmt = $db->prepare('SELECT
        (SELECT COUNT(*) FROM patients WHERE tenant_id = ?) AS patients,
        (SELECT COUNT(*) FROM lab_orders WHERE tenant_id = ?) AS orders,
        (SELECT COUNT(*) FROM lab_orders WHERE tenant_id = ? AND DATE(created_at) = CURDATE()) AS today_orders,
        (SELECT COUNT(*) FROM lab_orders WHERE tenant_id = ? AND status = ?) AS completed_orders,
        (SELECT COALESCE(SUM(i.net_amount), 0) FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE o.tenant_id = ?) AS revenue,
        (SELECT COALESCE(SUM(i.net_amount), 0) FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE o.tenant_id = ? AND DATE(i.created_at) = CURDATE()) AS today_revenue,
        (SELECT COUNT(*) FROM users WHERE tenant_id = ?) AS users,
        (SELECT COUNT(*) FROM users WHERE tenant_id = ? AND is_active = 1) AS active_users,
        (SELECT COUNT(*) FROM branches WHERE tenant_id = ?) AS branches,
        (SELECT COUNT(*) FROM branches WHERE tenant_id = ? AND is_active = 1) AS active_branches,
        (SELECT COUNT(*) FROM tests WHERE tenant_id = ?) AS tests,
        (SELECT COUNT(*) FROM doctors WHERE tenant_id = ?) AS doctors');
    $stmt->execute([$id, $id, $id, $id, 'completed', $id, $id, $id, $id, $id, $id, $id, $id]);
    $stats = $stmt->fetch();
    
    // آخر الطلبات
    $recentOrders = [];
    try {
        $stmt = $db->prepare('SELECT o.id, o.order_number, o.order_date, o.status, p.full_name AS patient_name FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE o.tenant_id = ? ORDER BY o.id DESC LIMIT 10');
        $stmt->execute([$id]);
        $recentOrders = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // معلومات المدير
    $admin = null;
    try {
        $stmt = $db->prepare('SELECT u.id, u.full_name, u.username, u.email, u.phone, u.last_login_at, u.created_at FROM users u WHERE u.tenant_id = ? AND u.role_id = 1 ORDER BY u.id ASC LIMIT 1');
        $stmt->execute([$id]);
        $admin = $stmt->fetch();
    } catch (Throwable $e) {}
    
    $statusLabels = [
        'active' => 'نشط',
        'trial' => 'تجريبي',
        'suspended' => 'موقوف'
    ];
    
    ?>
    <div class="page-header">
        <h1><?php echo htmlspecialchars($tenant['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <div class="actions-bar">
            <a href="index.php?page=admin_tenants&action=edit&id=<?php echo $id; ?>" class="btn-primary">✏️ تعديل</a>
            <a href="index.php?switch_tenant=<?php echo $id; ?>&page=dashboard" class="btn-secondary">🚀 فتح المختبر</a>
            <?php if ($id !== 1): ?>
            <a href="index.php?page=admin_tenants&action=delete_confirm&id=<?php echo $id; ?>" class="btn-secondary" style="color:var(--danger);">🗑️ حذف</a>
            <?php endif; ?>
            <a href="index.php?page=admin_tenants" class="btn-secondary">← رجوع</a>
        </div>
    </div>
    
    <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((int)($stats['patients'] ?? 0)); ?></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((int)($stats['orders'] ?? 0)); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">الطلبات</div>
            <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;"><?php echo (int)($stats['today_orders'] ?? 0); ?> اليوم</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)($stats['revenue'] ?? 0), 2); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">إجمالي الإيرادات</div>
            <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;"><?php echo number_format((float)($stats['today_revenue'] ?? 0), 2); ?> اليوم</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--warning);"><?php echo (int)($stats['users'] ?? 0); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">المستخدمون</div>
            <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;"><?php echo (int)($stats['active_users'] ?? 0); ?> نشط</div>
        </div>
        <div class="card" style="text-align:center;">
            <div style="font-size:2rem;font-weight:bold;color:var(--danger);"><?php echo (int)($stats['branches'] ?? 0); ?></div>
            <div style="color:var(--text-muted);margin-top:4px;">الفروع</div>
            <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;"><?php echo (int)($stats['active_branches'] ?? 0); ?> نشط</div>
        </div>
    </div>
    
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
        <?php
        $viewBaseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
        $viewScriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/index.php'));
        if ($viewScriptDir === '/' || $viewScriptDir === '\\') $viewScriptDir = '';
        $viewLoginUrl = rtrim($viewBaseUrl . $viewScriptDir, '/') . '/index.php?page=login&tenant=' . urlencode($tenant['slug'] ?? '');
        ?>
        <div class="card">
            <h3 style="margin-top:0;">معلومات المختبر</h3>
            <table style="width:100%;">
                <tr><td style="padding:8px 0;font-weight:bold;width:40%;">الاسم:</td><td><?php echo htmlspecialchars($tenant['name'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">الرابط:</td><td><code><?php echo htmlspecialchars($tenant['slug'], ENT_QUOTES, 'UTF-8'); ?></code></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">رابط الدخول لأبواب المختبر:</td><td>
                    <input type="text" readonly value="<?php echo htmlspecialchars($viewLoginUrl, ENT_QUOTES, 'UTF-8'); ?>" style="width:100%;max-width:400px;font-size:0.9rem;padding:8px;border:1px solid var(--border);border-radius:4px;background:var(--bg-secondary);" id="view-login-link">
                    <button type="button" onclick="navigator.clipboard.writeText(document.getElementById('view-login-link').value);this.textContent='✓ تم النسخ';setTimeout(()=>this.textContent='📋 نسخ الرابط',2000)" class="btn-primary" style="margin-top:8px;">📋 نسخ الرابط</button>
                </td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">الحالة:</td><td><span class="badge badge-<?php echo ($tenant['status'] ?? '') === 'active' ? 'completed' : (($tenant['status'] ?? '') === 'suspended' ? 'cancelled' : 'warning'); ?>"><?php echo htmlspecialchars($statusLabels[$tenant['status'] ?? 'trial'] ?? 'تجريبي', ENT_QUOTES, 'UTF-8'); ?></span></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">الخطة:</td><td><?php echo htmlspecialchars($tenant['plan_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">تاريخ التسجيل:</td><td><?php echo date('Y-m-d H:i', strtotime($tenant['created_at'])); ?></td></tr>
                <?php if (!empty($tenant['primary_color'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">اللون الأساسي:</td><td><span style="display:inline-block;width:20px;height:20px;background:<?php echo htmlspecialchars($tenant['primary_color'], ENT_QUOTES, 'UTF-8'); ?>;border-radius:4px;vertical-align:middle;margin-left:8px;"></span> <?php echo htmlspecialchars($tenant['primary_color'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
            </table>
        </div>
        
        <div class="card">
            <h3 style="margin-top:0;">معلومات المدير</h3>
            <?php if ($admin): ?>
            <table style="width:100%;">
                <tr><td style="padding:8px 0;font-weight:bold;width:40%;">الاسم:</td><td><?php echo htmlspecialchars($admin['full_name'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <tr><td style="padding:8px 0;font-weight:bold;">اسم المستخدم:</td><td><code><?php echo htmlspecialchars($admin['username'], ENT_QUOTES, 'UTF-8'); ?></code></td></tr>
                <?php if (!empty($admin['email'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">البريد:</td><td><?php echo htmlspecialchars($admin['email'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($admin['phone'])): ?>
                <tr><td style="padding:8px 0;font-weight:bold;">الهاتف:</td><td><?php echo htmlspecialchars($admin['phone'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
                <?php endif; ?>
                <tr><td style="padding:8px 0;font-weight:bold;">آخر دخول:</td><td><?php echo $admin['last_login_at'] ? date('Y-m-d H:i', strtotime($admin['last_login_at'])) : 'لم يسجل دخول'; ?></td></tr>
            </table>
            <?php else: ?>
            <p style="color:var(--text-muted);">لا توجد معلومات المدير</p>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if (!empty($recentOrders)): ?>
    <div class="card" style="margin-top: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>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentOrders as $order): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo date('Y-m-d H:i', strtotime($order['order_date'])); ?></td>
                        <td><span class="badge badge-<?php echo $order['status'] === 'completed' ? 'completed' : ($order['status'] === 'cancelled' ? 'cancelled' : 'warning'); ?>"><?php echo htmlspecialchars($order['status'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                        <td><a href="index.php?switch_tenant=<?php echo $id; ?>&page=orders&order_id=<?php echo (int)$order['id']; ?>" class="btn-link">عرض</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    
    <?php
    return;
}

// عرض نموذج التعديل
if ($action === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0 || $id === 1) {
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    
    $stmt = $db->prepare('SELECT * FROM tenants WHERE id = ?');
    $stmt->execute([$id]);
    $tenant = $stmt->fetch();
    
    if (!$tenant) {
        header('Location: index.php?page=admin_tenants');
        exit;
    }
    
    $plans = [];
    try {
        $plans = $db->query('SELECT id, name, max_branches, max_users FROM subscription_plans ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>تعديل مختبر: <?php echo htmlspecialchars($tenant['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
    </div>
    
    <div class="card">
        <form method="post" class="form-grid">
            <input type="hidden" name="id" value="<?php echo (int)$tenant['id']; ?>">
            <div class="full-width">
                <label>اسم المختبر <span style="color:red;">*</span></label>
                <input type="text" name="lab_name" required value="<?php echo htmlspecialchars($tenant['name'], ENT_QUOTES, 'UTF-8'); ?>" minlength="2">
            </div>
            <div>
                <label>الرابط (slug) <span style="color:red;">*</span></label>
                <input type="text" name="slug" required pattern="[a-z0-9_-]+" value="<?php echo htmlspecialchars($tenant['slug'], ENT_QUOTES, 'UTF-8'); ?>" minlength="2">
                <small style="color:var(--text-muted);">للوصول: <?php echo htmlspecialchars($tenant['slug'], ENT_QUOTES, 'UTF-8'); ?>.yourdomain.com</small>
            </div>
            <div>
                <label>الخطة</label>
                <select name="plan_id">
                    <?php foreach ($plans as $p): ?>
                    <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$tenant['plan_id'] === (int)$p['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($p['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label>الحالة</label>
                <select name="status">
                    <option value="active" <?php echo ($tenant['status'] ?? '') === 'active' ? 'selected' : ''; ?>>نشط</option>
                    <option value="trial" <?php echo ($tenant['status'] ?? '') === 'trial' ? 'selected' : ''; ?>>تجريبي</option>
                    <option value="suspended" <?php echo ($tenant['status'] ?? '') === 'suspended' ? 'selected' : ''; ?>>موقوف</option>
                </select>
            </div>
            <div>
                <label>اللون الأساسي</label>
                <div style="display:flex;gap:8px;align-items:center;">
                    <input type="color" name="primary_color" value="<?php echo htmlspecialchars($tenant['primary_color'] ?? '#0d9488', ENT_QUOTES, 'UTF-8'); ?>" style="width:60px;height:40px;">
                    <input type="text" name="primary_color" value="<?php echo htmlspecialchars($tenant['primary_color'] ?? '#0d9488', ENT_QUOTES, 'UTF-8'); ?>" pattern="^#[0-9a-fA-F]{6}$" style="flex:1;">
                </div>
            </div>
            <div class="full-width">
                <label>رابط الشعار (Logo URL)</label>
                <input type="url" name="logo_url" value="<?php echo htmlspecialchars($tenant['logo_url'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="https://example.com/logo.png">
            </div>
            <div class="full-width">
                <label>ملاحظات</label>
                <textarea name="notes" rows="3"><?php echo htmlspecialchars($tenant['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
            </div>
            <div class="full-width form-actions">
                <button type="submit" class="btn-primary">💾 حفظ التعديلات</button>
                <a href="index.php?page=admin_tenants&action=view&id=<?php echo (int)$tenant['id']; ?>" class="btn-secondary">👁️ عرض التفاصيل</a>
                <a href="index.php?page=admin_tenants" class="btn-secondary">← رجوع</a>
            </div>
        </form>
    </div>
    <?php
    return;
}

// الرسائل
$msg = $_SESSION['admin_msg'] ?? '';
$err = $_SESSION['admin_error'] ?? '';
unset($_SESSION['admin_msg'], $_SESSION['admin_error']);

// جلب الخطط
$plans = [];
try {
    $plans = $db->query('SELECT id, name, max_branches, max_users, price_monthly FROM subscription_plans ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

// البحث والفلاتر
$search = trim($_GET['q'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$planFilter = (int)($_GET['plan_id'] ?? 0);
$export = isset($_GET['export']) && $_GET['export'] === 'csv';

// جلب المختبرات
$tenants = [];
$totalStats = ['total' => 0, 'active' => 0, 'trial' => 0, 'suspended' => 0, 'total_revenue' => 0];

try {
    $sql = "SELECT t.id, t.slug, t.name, t.status, t.created_at, t.primary_color, p.name AS plan_name, p.price_monthly
           FROM tenants t
           LEFT JOIN subscription_plans p ON p.id = t.plan_id
           WHERE 1=1";
    $params = [];
    
    if ($search !== '') {
        $sql .= ' AND (t.name LIKE ? OR t.slug LIKE ?)';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
    }
    
    if ($statusFilter !== '') {
        $sql .= ' AND t.status = ?';
        $params[] = $statusFilter;
    }
    
    if ($planFilter > 0) {
        $sql .= ' AND t.plan_id = ?';
        $params[] = $planFilter;
    }
    
    $sql .= ' ORDER BY t.id ASC';
    
    if ($export) {
        $stmt = $params ? $db->prepare($sql) : $db->query($sql);
        if ($params) $stmt->execute($params);
        $tenants = $stmt->fetchAll();
        
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="tenants_' . date('Y-m-d') . '.csv"');
        echo "\xEF\xBB\xBF";
        echo "ID,الاسم,الرابط,الحالة,الخطة,المرضى,الطلبات,الإيرادات,المستخدمون,الفروع,التسجيل\n";
        foreach ($tenants as $t) {
            $tid = (int)$t['id'];
            $row = $db->prepare('SELECT
                (SELECT COUNT(*) FROM patients WHERE tenant_id = ?) AS patients,
                (SELECT COUNT(*) FROM lab_orders WHERE tenant_id = ?) AS orders,
                (SELECT COALESCE(SUM(i.net_amount), 0) FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE o.tenant_id = ?) AS revenue,
                (SELECT COUNT(*) FROM users WHERE tenant_id = ?) AS users,
                (SELECT COUNT(*) FROM branches WHERE tenant_id = ?) AS branches');
            $row->execute([$tid, $tid, $tid, $tid, $tid]);
            $s = $row->fetch();
            
            $line = [
                $tid,
                $t['name'],
                $t['slug'],
                $t['status'] === 'active' ? 'نشط' : ($t['status'] === 'suspended' ? 'موقوف' : 'تجريبي'),
                $t['plan_name'] ?? '-',
                (int)($s['patients'] ?? 0),
                (int)($s['orders'] ?? 0),
                number_format((float)($s['revenue'] ?? 0), 2),
                (int)($s['users'] ?? 0),
                (int)($s['branches'] ?? 0),
                $t['created_at']
            ];
            $escaped = [];
            foreach ($line as $v) {
                $v = (string)$v;
                if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
                $escaped[] = $v;
            }
            echo implode(',', $escaped) . "\n";
        }
        exit;
    }
    
    $stmt = $params ? $db->prepare($sql) : $db->query($sql);
    if ($params) $stmt->execute($params);
    $tenants = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($tenants as &$t) {
        $tid = (int)$t['id'];
        $row = $db->prepare('SELECT
            (SELECT COUNT(*) FROM patients WHERE tenant_id = ?) AS patients,
            (SELECT COUNT(*) FROM lab_orders WHERE tenant_id = ?) AS orders,
            (SELECT COALESCE(SUM(i.net_amount), 0) FROM invoices i JOIN lab_orders o ON o.id = i.order_id WHERE o.tenant_id = ?) AS revenue,
            (SELECT COUNT(*) FROM users WHERE tenant_id = ?) AS users,
            (SELECT COUNT(*) FROM branches WHERE tenant_id = ?) AS branches');
        $row->execute([$tid, $tid, $tid, $tid, $tid]);
        $s = $row->fetch(PDO::FETCH_ASSOC);
        $t['patients'] = (int)($s['patients'] ?? 0);
        $t['orders'] = (int)($s['orders'] ?? 0);
        $t['revenue'] = (float)($s['revenue'] ?? 0);
        $t['users'] = (int)($s['users'] ?? 0);
        $t['branches'] = (int)($s['branches'] ?? 0);
        
        // إحصائيات إجمالية
        $totalStats['total']++;
        if ($t['status'] === 'active') $totalStats['active']++;
        elseif ($t['status'] === 'trial') $totalStats['trial']++;
        elseif ($t['status'] === 'suspended') $totalStats['suspended']++;
        $totalStats['total_revenue'] += $t['revenue'];
    }
} catch (Throwable $e) {}
?>
<div class="page-header">
    <h1>إدارة المختبرات</h1>
    <span style="color:var(--text-muted);font-size:0.9rem;">لوحة مدير المنصة</span>
    <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
        <form method="get" style="display:inline-flex;gap:6px;flex-wrap:wrap;">
            <input type="hidden" name="page" value="admin_tenants">
            <input type="search" name="q" placeholder="بحث..." value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;">
            <select name="status" style="min-width:120px;">
                <option value="">جميع الحالات</option>
                <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>نشط</option>
                <option value="trial" <?php echo $statusFilter === 'trial' ? 'selected' : ''; ?>>تجريبي</option>
                <option value="suspended" <?php echo $statusFilter === 'suspended' ? 'selected' : ''; ?>>موقوف</option>
            </select>
            <select name="plan_id" style="min-width:150px;">
                <option value="0">جميع الخطط</option>
                <?php foreach ($plans as $p): ?>
                <option value="<?php echo (int)$p['id']; ?>" <?php echo $planFilter === (int)$p['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($p['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
            <button type="submit">بحث</button>
            <?php if ($search || $statusFilter || $planFilter): ?>
            <a href="index.php?page=admin_tenants" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </form>
        <a href="index.php?page=admin_tenants&export=csv<?php echo $search ? '&q=' . urlencode($search) : ''; echo $statusFilter ? '&status=' . urlencode($statusFilter) : ''; echo $planFilter ? '&plan_id=' . $planFilter : ''; ?>" class="btn-secondary">📥 تصدير CSV</a>
        <button onclick="document.getElementById('createForm').scrollIntoView({behavior:'smooth'});" class="btn-primary">➕ مختبر جديد</button>
    </div>
</div>

<?php if ($msg): ?>
<div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php if ($err): ?>
<div class="alert alert-danger" style="margin-bottom:16px;"><?php echo htmlspecialchars($err, ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>

<?php
$recentSignups = [];
try {
    $stmt = $db->prepare('SELECT r.*, p.name AS plan_name FROM lab_signup_requests r LEFT JOIN subscription_plans p ON p.id = r.plan_id ORDER BY r.created_at DESC LIMIT 10');
    $stmt->execute();
    $recentSignups = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}
if (!empty($recentSignups)): ?>
<div class="card" style="margin-bottom:24px;border-right:4px solid var(--primary);">
    <h3 style="margin-top:0;">📋 طلبات التسجيل الجديدة (آخر 10)</h3>
    <p style="color:var(--text-muted);margin-bottom:16px;">طلبات التسجيل الذاتية تصل هنا مباشرة مع كل البيانات للتواصل.</p>
    <div class="table-wrapper" style="overflow-x:auto;">
    <table class="table" style="font-size:0.9rem;">
        <thead>
            <tr>
                <th>التاريخ</th>
                <th>المختبر</th>
                <th>الرابط</th>
                <th>المدير</th>
                <th>الهاتف</th>
                <th>البريد</th>
                <th>الخطة</th>
                <th>إجراء</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($recentSignups as $r): ?>
            <tr>
                <td><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($r['created_at'] ?? '')), ENT_QUOTES, 'UTF-8'); ?></td>
                <td><strong><?php echo htmlspecialchars($r['lab_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></strong></td>
                <td><code><?php echo htmlspecialchars($r['slug'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></code></td>
                <td><?php echo htmlspecialchars($r['admin_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                <td><?php if (!empty($r['admin_phone'])): ?><a href="tel:<?php echo htmlspecialchars($r['admin_phone'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($r['admin_phone'], ENT_QUOTES, 'UTF-8'); ?></a><?php else: ?>—<?php endif; ?></td>
                <td><?php if (!empty($r['admin_email'])): ?><a href="mailto:<?php echo htmlspecialchars($r['admin_email'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($r['admin_email'], ENT_QUOTES, 'UTF-8'); ?></a><?php else: ?>—<?php endif; ?></td>
                <td><?php echo htmlspecialchars($r['plan_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                <td><a href="index.php?page=admin_tenants&action=view&id=<?php echo (int)($r['tenant_id'] ?? 0); ?>" class="btn-link">عرض</a></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</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 $totalStats['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 $totalStats['active']; ?></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 $totalStats['trial']; ?></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($totalStats['total_revenue'], 2); ?></div>
        <div style="color:var(--text-muted);margin-top:4px;">إجمالي الإيرادات</div>
    </div>
</div>

<div class="card" id="createForm" style="margin-bottom:24px;">
    <h3 style="margin-top:0;">إضافة مختبر جديد</h3>
    <form method="post" action="index.php?page=admin_tenants&action=create" class="form-grid">
        <div>
            <label>اسم المختبر <span style="color:red;">*</span></label>
            <input type="text" name="lab_name" required placeholder="مختبر النور" minlength="2">
        </div>
        <div>
            <label>الرابط (slug) <span style="color:red;">*</span></label>
            <input type="text" name="slug" required pattern="[a-z0-9_-]+" placeholder="mylab" minlength="2">
            <small style="color:var(--text-muted);display:block;margin-top:4px;">للوصول: mylab.yourdomain.com</small>
        </div>
        <div>
            <label>اسم المدير <span style="color:red;">*</span></label>
            <input type="text" name="admin_name" required placeholder="أحمد محمد" minlength="2">
        </div>
        <div>
            <label>اسم المستخدم <span style="color:red;">*</span></label>
            <input type="text" name="username" required placeholder="admin" minlength="3">
        </div>
        <div>
            <label>كلمة المرور <span style="color:red;">*</span></label>
            <input type="password" name="password" required minlength="6" placeholder="6 أحرف على الأقل">
        </div>
        <div>
            <label>البريد الإلكتروني</label>
            <input type="email" name="email" placeholder="admin@example.com">
        </div>
        <div>
            <label>الهاتف</label>
            <input type="text" name="phone" placeholder="05xxxxxxxx">
        </div>
        <div>
            <label>الخطة</label>
            <select name="plan_id">
                <?php foreach ($plans as $p): ?>
                <option value="<?php echo (int)$p['id']; ?>">
                    <?php echo htmlspecialchars($p['name'] ?? '', ENT_QUOTES, 'UTF-8'); ?> 
                    (<?php echo (int)($p['max_branches'] ?? 1); ?> فرع، <?php echo (int)($p['max_users'] ?? 5); ?> مستخدم)
                    <?php if (!empty($p['price_monthly'])): ?> - <?php echo number_format((float)$p['price_monthly'], 2); ?> د.ع/شهر<?php endif; ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>الحالة</label>
            <select name="status">
                <option value="trial">تجريبي</option>
                <option value="active">نشط</option>
                <option value="suspended">موقوف</option>
            </select>
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">✅ إنشاء المختبر</button>
        </div>
    </form>
</div>

<?php
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/index.php'));
if ($scriptDir === '/' || $scriptDir === '\\') $scriptDir = '';
$loginBase = rtrim($baseUrl . $scriptDir, '/') . '/index.php';
?>
<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>
            <th>المستخدمون</th>
            <th>الفروع</th>
            <th>التسجيل</th>
            <th>إجراءات</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($tenants)): ?>
        <tr><td colspan="13" style="text-align:center;padding:24px;color:var(--text-muted);">لا توجد مختبرات</td></tr>
        <?php else: ?>
        <?php foreach ($tenants as $t):
            $loginUrl = $loginBase . '?page=login&tenant=' . urlencode($t['slug'] ?? '');
        ?>
        <tr>
            <td><?php echo (int)$t['id']; ?></td>
            <td><strong><?php echo htmlspecialchars($t['name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></strong></td>
            <td><code style="font-size:0.85rem;"><?php echo htmlspecialchars($t['slug'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></code></td>
            <td style="max-width:220px;">
                <input type="text" readonly value="<?php echo htmlspecialchars($loginUrl, ENT_QUOTES, 'UTF-8'); ?>" style="width:100%;font-size:0.75rem;padding:4px 8px;border:1px solid var(--border);border-radius:4px;background:var(--bg-secondary);" id="link-<?php echo (int)$t['id']; ?>">
                <button type="button" onclick="navigator.clipboard.writeText(document.getElementById('link-<?php echo (int)$t['id']; ?>').value);this.textContent='✓ تم';setTimeout(()=>this.textContent='نسخ',1500)" class="btn-link" style="margin-top:4px;font-size:0.8rem;">📋 نسخ</button>
            </td>
            <td>
                <span class="badge badge-<?php echo ($t['status'] ?? '') === 'active' ? 'completed' : (($t['status'] ?? '') === 'suspended' ? 'cancelled' : 'warning'); ?>">
                    <?php echo ($t['status'] ?? '') === 'active' ? 'نشط' : (($t['status'] ?? '') === 'suspended' ? 'موقوف' : 'تجريبي'); ?>
                </span>
            </td>
            <td><?php echo htmlspecialchars($t['plan_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo number_format($t['patients'] ?? 0); ?></td>
            <td><?php echo number_format($t['orders'] ?? 0); ?></td>
            <td><?php echo number_format($t['revenue'] ?? 0, 2); ?> د.ع</td>
            <td><?php echo (int)($t['users'] ?? 0); ?></td>
            <td><?php echo (int)($t['branches'] ?? 0); ?></td>
            <td><?php echo date('Y-m-d', strtotime($t['created_at'])); ?></td>
            <td>
                <a href="index.php?page=admin_tenants&action=view&id=<?php echo (int)$t['id']; ?>" class="btn-link" title="عرض التفاصيل">👁️</a>
                <?php if ((int)$t['id'] !== 1): ?>
                    <a href="index.php?page=admin_tenants&action=edit&id=<?php echo (int)$t['id']; ?>" class="btn-link" title="تعديل">✏️</a>
                    <a href="index.php?page=admin_tenants&action=delete_confirm&id=<?php echo (int)$t['id']; ?>" class="btn-link" title="حذف" style="color:var(--danger);">🗑️</a>
                <?php endif; ?>
                <a href="index.php?switch_tenant=<?php echo (int)$t['id']; ?>&page=dashboard" class="btn-link" title="فتح المختبر">🚀</a>
                <?php if ((int)$t['id'] !== 1): ?>
                <form method="post" action="index.php?page=admin_tenants&action=toggle_status&id=<?php echo (int)$t['id']; ?>" style="display:inline;">
                    <select name="status" onchange="this.form.submit()" style="padding:2px 6px;font-size:0.8rem;border:1px solid var(--border);border-radius:4px;">
                        <option value="active" <?php echo ($t['status'] ?? '') === 'active' ? 'selected' : ''; ?>>نشط</option>
                        <option value="trial" <?php echo ($t['status'] ?? '') === 'trial' ? 'selected' : ''; ?>>تجريبي</option>
                        <option value="suspended" <?php echo ($t['status'] ?? '') === 'suspended' ? 'selected' : ''; ?>>موقوف</option>
                    </select>
                </form>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>
</div>

<p style="color:var(--text-muted);margin-top:16px;">
    💡 <strong>ملاحظة:</strong> كل مختبر له بياناته المعزولة تماماً. استخدم "فتح" للتنقل لمختبر معيّن.
</p>
