<?php
/**
 * لوحة Super Admin - إدارة حسابات الأطباء وربطهم بالمختبرات
 * إنشاء حسابات دخول للأطباء للوصول إلى بوابة Smart Doctor
 */
use App\Core\Auth;
use App\Core\Csrf;
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);
$q = trim($_GET['q'] ?? '');
$statusFilter = $_GET['status'] ?? '';
$tenantFilter = (int)($_GET['tenant_id'] ?? 0);
$sort = $_GET['sort'] ?? 'created_at';
$dir = strtolower($_GET['dir'] ?? 'desc') === 'asc' ? 'asc' : 'desc';
$pageNo = max(1, (int)($_GET['p'] ?? 1));
$perPage = (int)($_GET['per_page'] ?? 20);
if (!in_array($perPage, [10, 20, 50, 100], true)) $perPage = 20;

$sortMap = [
    'doctor' => 'd.full_name',
    'tenant' => 't.name',
    'username' => 'da.username',
    'last_login' => 'da.last_login_at',
    'status' => 'da.is_active',
    'created_at' => 'da.created_at',
];
if (!isset($sortMap[$sort])) $sort = 'created_at';
$sortSql = $sortMap[$sort] . ' ' . strtoupper($dir);

$returnQuery = http_build_query([
    'q' => $q,
    'status' => $statusFilter,
    'tenant_id' => $tenantFilter > 0 ? $tenantFilter : null,
    'sort' => $sort,
    'dir' => $dir,
    'p' => $pageNo > 1 ? $pageNo : null,
    'per_page' => $perPage !== 20 ? $perPage : null,
]);
$returnQuery = ltrim((string)$returnQuery, '&');

function doctorAccountsRedirect(string $returnQuery): void {
    $suffix = '';
    if ($returnQuery !== '' && preg_match('/^[a-zA-Z0-9_\-\=&%\.]*$/', $returnQuery)) {
        $suffix = '&' . $returnQuery;
    }
    header('Location: index.php?page=admin_doctor_accounts' . $suffix);
    exit;
}

// إنشاء الجداول إن لم تكن موجودة
try { $db->query('SELECT id FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/../migrations/022_doctor_portal.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/../migrations/023_doctor_reminders_favorites.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
// دعم الحسابات غير المرتبطة: السماح بأن تكون doctor_id/tenant_id فارغة
try { $db->exec('ALTER TABLE doctor_accounts MODIFY doctor_id INT NULL'); } catch (Throwable $e) {}
try { $db->exec('ALTER TABLE doctor_accounts MODIFY tenant_id INT NULL'); } catch (Throwable $e) {}

// إنشاء حساب طبيب جديد
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $tenantIdSel = (int)($_POST['tenant_id'] ?? 0);
    $doctorIdSel = (int)($_POST['doctor_id'] ?? 0);
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    $err = '';
    if (($tenantIdSel > 0 && $doctorIdSel <= 0) || ($tenantIdSel <= 0 && $doctorIdSel > 0)) {
        $err = 'عند اختيار مختبر يجب اختيار طبيب منه (أو اترك الاثنين بدون ربط).';
    }
    elseif (strlen($username) < 3) $err = 'اسم المستخدم 3 أحرف على الأقل.';
    elseif (strlen($password) < 6) $err = 'كلمة المرور 6 أحرف على الأقل.';

    if ($err) {
        $_SESSION['doctor_acc_error'] = $err;
    } else {
        try {
            $stmt = $db->prepare('SELECT id FROM doctor_accounts WHERE username = ?');
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $_SESSION['doctor_acc_error'] = 'اسم المستخدم مستخدم. اختر آخر.';
            } else {
                if ($tenantIdSel > 0 && $doctorIdSel > 0) {
                    $stmt = $db->prepare('SELECT id FROM doctors WHERE id = ? AND tenant_id = ?');
                    $stmt->execute([$doctorIdSel, $tenantIdSel]);
                    if (!$stmt->fetch()) {
                        $_SESSION['doctor_acc_error'] = 'الطبيب غير موجود في هذا المختبر.';
                    } else {
                        $stmt = $db->prepare('SELECT id FROM doctor_accounts WHERE doctor_id = ? AND tenant_id = ?');
                        $stmt->execute([$doctorIdSel, $tenantIdSel]);
                        if ($stmt->fetch()) {
                            $_SESSION['doctor_acc_error'] = 'هذا الطبيب لديه حساب مسبقاً في هذا المختبر.';
                        }
                    }
                }
                if (!isset($_SESSION['doctor_acc_error'])) {
                    $hash = password_hash($password, PASSWORD_BCRYPT);
                    $stmt = $db->prepare('INSERT INTO doctor_accounts (doctor_id, tenant_id, username, password_hash, is_active, created_by) VALUES (?, ?, ?, ?, 1, ?)');
                    $stmt->execute([
                        $doctorIdSel > 0 ? $doctorIdSel : null,
                        $tenantIdSel > 0 ? $tenantIdSel : null,
                        $username,
                        $hash,
                        $_SESSION['user_id'] ?? null
                    ]);
                    $_SESSION['doctor_acc_msg'] = ($tenantIdSel > 0 && $doctorIdSel > 0)
                        ? 'تم إنشاء الحساب وربطه بالمختبر بنجاح.'
                        : 'تم إنشاء حساب غير مرتبط. يمكنك ربطه لاحقاً.';
                    if (isset($auditLog)) {
                        $auditLog->log('doctor_account_created', 'doctor_account', (int)$db->lastInsertId(), null, json_encode(['username' => $username, 'doctor_id' => $doctorIdSel > 0 ? $doctorIdSel : null, 'tenant_id' => $tenantIdSel > 0 ? $tenantIdSel : null], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                    }
                }
            }
        } catch (Throwable $e) {
            $_SESSION['doctor_acc_error'] = 'خطأ: ' . $e->getMessage();
        }
    }
    doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
}

// تعديل / تفعيل / تعطيل
if ($action === 'toggle' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $active = (int)($_POST['is_active'] ?? 0);
    try {
        $db->prepare('UPDATE doctor_accounts SET is_active = ? WHERE id = ?')->execute([$active, $editId]);
        $_SESSION['doctor_acc_msg'] = 'تم التحديث.';
    } catch (Throwable $e) {
        $_SESSION['doctor_acc_error'] = 'فشل التحديث.';
    }
    doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
}

// إعادة تعيين كلمة المرور
if ($action === 'reset_password' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $newPass = $_POST['new_password'] ?? '';
    if (strlen($newPass) >= 6) {
        try {
            $hash = password_hash($newPass, PASSWORD_BCRYPT);
            $db->prepare('UPDATE doctor_accounts SET password_hash = ? WHERE id = ?')->execute([$hash, $editId]);
            $_SESSION['doctor_acc_msg'] = 'تم تغيير كلمة المرور.';
        } catch (Throwable $e) {
            $_SESSION['doctor_acc_error'] = 'فشل التحديث.';
        }
    } else {
        $_SESSION['doctor_acc_error'] = 'كلمة المرور 6 أحرف على الأقل.';
    }
    doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
}

// حذف
if ($action === 'delete' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    try {
        $db->prepare('DELETE FROM doctor_accounts WHERE id = ?')->execute([$editId]);
        $_SESSION['doctor_acc_msg'] = 'تم حذف الحساب.';
    } catch (Throwable $e) {
        $_SESSION['doctor_acc_error'] = 'فشل الحذف.';
    }
    doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
}

// تعديل الربط بين الحساب والطبيب/المختبر (أو فك الربط)
if ($action === 'update_link' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $tenantIdSel = (int)($_POST['tenant_id'] ?? 0);
    $doctorIdSel = (int)($_POST['doctor_id'] ?? 0);

    if (($tenantIdSel > 0 && $doctorIdSel <= 0) || ($tenantIdSel <= 0 && $doctorIdSel > 0)) {
        $_SESSION['doctor_acc_error'] = 'عند اختيار مختبر يجب اختيار طبيب منه (أو اترك الاثنين بدون ربط).';
        doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
    }

    try {
        if ($tenantIdSel > 0 && $doctorIdSel > 0) {
            $stmt = $db->prepare('SELECT id FROM doctors WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$doctorIdSel, $tenantIdSel]);
            if (!$stmt->fetch()) {
                $_SESSION['doctor_acc_error'] = 'الطبيب غير موجود في هذا المختبر.';
                doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
            }

            $stmt = $db->prepare('SELECT id FROM doctor_accounts WHERE doctor_id = ? AND tenant_id = ? AND id <> ?');
            $stmt->execute([$doctorIdSel, $tenantIdSel, $editId]);
            if ($stmt->fetch()) {
                $_SESSION['doctor_acc_error'] = 'يوجد حساب آخر مرتبط بنفس الطبيب والمختبر.';
                doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
            }
        }

        $stmt = $db->prepare('UPDATE doctor_accounts SET doctor_id = ?, tenant_id = ? WHERE id = ?');
        $stmt->execute([
            $doctorIdSel > 0 ? $doctorIdSel : null,
            $tenantIdSel > 0 ? $tenantIdSel : null,
            $editId
        ]);
        $_SESSION['doctor_acc_msg'] = ($tenantIdSel > 0 && $doctorIdSel > 0) ? 'تم تحديث الربط بنجاح.' : 'تم فك الربط عن المختبر والطبيب.';
    } catch (Throwable $e) {
        $_SESSION['doctor_acc_error'] = 'فشل تحديث الربط.';
    }
    doctorAccountsRedirect($_POST['return_query'] ?? $returnQuery);
}

$msg = $_SESSION['doctor_acc_msg'] ?? '';
$err = $_SESSION['doctor_acc_error'] ?? '';
unset($_SESSION['doctor_acc_msg'], $_SESSION['doctor_acc_error']);

$accounts = [];
$stats = [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
    'logged_in' => 0,
];
$totalRows = 0;
$totalPages = 1;
try {
    $fromSql = ' FROM doctor_accounts da
                 LEFT JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id
                 LEFT JOIN tenants t ON t.id = da.tenant_id
                 WHERE 1=1';
    $params = [];
    if ($tenantFilter > 0) {
        $fromSql .= ' AND da.tenant_id = ?';
        $params[] = $tenantFilter;
    }
    if ($statusFilter === 'active') {
        $fromSql .= ' AND da.is_active = 1';
    } elseif ($statusFilter === 'inactive') {
        $fromSql .= ' AND da.is_active = 0';
    }
    if ($q !== '') {
        $fromSql .= ' AND (da.username LIKE ? OR d.full_name LIKE ? OR d.specialty LIKE ? OR t.name LIKE ?)';
        $like = '%' . $q . '%';
        $params = array_merge($params, [$like, $like, $like, $like]);
    }

    $statsStmt = $db->prepare('SELECT COUNT(*) AS total,
                                      SUM(CASE WHEN da.is_active = 1 THEN 1 ELSE 0 END) AS active_count,
                                      SUM(CASE WHEN da.is_active = 0 THEN 1 ELSE 0 END) AS inactive_count,
                                      SUM(CASE WHEN da.last_login_at IS NOT NULL THEN 1 ELSE 0 END) AS logged_in_count' . $fromSql);
    $statsStmt->execute($params);
    $statsRow = $statsStmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $stats['total'] = (int)($statsRow['total'] ?? 0);
    $stats['active'] = (int)($statsRow['active_count'] ?? 0);
    $stats['inactive'] = (int)($statsRow['inactive_count'] ?? 0);
    $stats['logged_in'] = (int)($statsRow['logged_in_count'] ?? 0);

    $totalRows = $stats['total'];
    $totalPages = max(1, (int)ceil($totalRows / $perPage));
    if ($pageNo > $totalPages) $pageNo = $totalPages;
    $offset = ($pageNo - 1) * $perPage;

    $sql = 'SELECT da.*, d.full_name AS doctor_name, d.specialty, d.clinic_name, t.name AS tenant_name, t.slug AS tenant_slug'
         . $fromSql
         . ' ORDER BY ' . $sortSql
         . ' LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

$tenants = [];
$doctorsByTenant = [];
try {
    $tenants = $db->query('SELECT id, name, slug FROM tenants WHERE status IN ("active","trial") ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);
    foreach ($tenants as $t) {
        $tid = (int)$t['id'];
        $stmt = $db->prepare('SELECT id, full_name, specialty, clinic_name FROM doctors WHERE tenant_id = ? ORDER BY full_name');
        $stmt->execute([$tid]);
        $doctorsByTenant[$tid] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {}

$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 = '';
$doctorPortalUrl = rtrim($baseUrl . $scriptDir, '/') . '/doctor.php';
?>
<style>
.doctor-accounts-page .page-header {
    margin-bottom: 18px;
}
.doctor-accounts-page .section-title {
    margin-top: 0;
    margin-bottom: 12px;
}
.doctor-accounts-page .page-subtitle {
    color: var(--text-muted);
    margin-top: 4px;
}
.doctor-accounts-page .actions-bar {
    gap: 8px;
    flex-wrap: wrap;
}
.doctor-accounts-page .card {
    border: 1px solid var(--border-color);
    border-radius: 14px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}
.doctor-accounts-page .mb-24 {
    margin-bottom: 24px;
}
.doctor-accounts-page .form-grid label {
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 6px;
    display: block;
}
.doctor-accounts-page .form-grid input,
.doctor-accounts-page .form-grid select {
    width: 100%;
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 10px 12px;
    background: var(--bg-primary);
}
.doctor-accounts-page .form-grid input:focus,
.doctor-accounts-page .form-grid select:focus {
    outline: none;
    border-color: #14b8a6;
    box-shadow: 0 0 0 3px rgba(20, 184, 166, 0.15);
}
.doctor-accounts-page .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
    gap: 12px;
    margin-bottom: 16px;
}
.doctor-accounts-page .stat-card {
    padding: 12px;
    border: 1px solid var(--border-color);
    border-radius: 12px;
    background: linear-gradient(180deg, var(--bg-secondary), var(--bg-primary));
}
.doctor-accounts-page .stat-label {
    font-size: 12px;
    color: var(--text-muted);
}
.doctor-accounts-page .stat-value {
    margin-top: 6px;
    font-size: 24px;
    font-weight: 800;
}
.doctor-accounts-page .filters-form {
    display: grid;
    grid-template-columns: 1.2fr 1fr 1fr 1fr 1fr 1fr auto;
    gap: 10px;
    align-items: end;
    margin-bottom: 14px;
    padding: 12px;
    border: 1px dashed var(--border-color);
    border-radius: 12px;
    background: var(--bg-secondary);
}
.doctor-accounts-page .results-meta {
    margin: 0 0 12px;
    color: var(--text-muted);
    font-size: 13px;
}
.doctor-accounts-page .table-wrapper {
    border: 1px solid var(--border-color);
    border-radius: 12px;
    overflow: hidden;
}
.doctor-accounts-page .table {
    margin: 0;
}
.doctor-accounts-page .table thead th {
    background: var(--bg-secondary);
    font-weight: 700;
    white-space: nowrap;
}
.doctor-accounts-page .table tbody tr:hover {
    background: rgba(20, 184, 166, 0.05);
}
.doctor-accounts-page .doctor-meta {
    color: var(--text-muted);
}
.doctor-accounts-page .actions-cell {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    align-items: center;
}
.doctor-accounts-page .btn-xs {
    padding: 5px 10px;
    font-size: 12px;
}
.doctor-accounts-page .btn-danger-text {
    color: #ef4444;
}
.doctor-accounts-page .reset-row {
    display: none;
    background: var(--bg-secondary);
}
.doctor-accounts-page .reset-cell {
    padding: 16px;
}
.doctor-accounts-page .reset-form {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
}
.doctor-accounts-page .pagination-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;
    gap: 10px;
    flex-wrap: wrap;
}
.doctor-accounts-page .pagination-meta {
    color: var(--text-muted);
    font-size: 13px;
}
.doctor-accounts-page .pagination-actions {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    align-items: center;
}
.doctor-accounts-page .page-number {
    min-width: 34px;
    text-align: center;
}
.doctor-accounts-page .page-number.active {
    background: #14b8a6;
    color: #fff;
    border-color: #14b8a6;
}
.doctor-accounts-page .btn-secondary.disabled {
    opacity: 0.5;
    pointer-events: none;
}
@media (max-width: 992px) {
    .doctor-accounts-page .actions-cell {
        min-width: 220px;
    }
}
@media (max-width: 1200px) {
    .doctor-accounts-page .filters-form {
        grid-template-columns: repeat(2, minmax(180px, 1fr));
    }
}
@media (max-width: 640px) {
    .doctor-accounts-page .filters-form {
        grid-template-columns: 1fr;
    }
}
</style>
<div class="doctor-accounts-page">
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>🩺 إدارة حسابات الأطباء</h1>
        <div class="actions-bar">
            <a href="index.php?page=admin_tenants" class="btn-secondary">← إدارة المختبرات</a>
            <a href="<?php echo htmlspecialchars($doctorPortalUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener noreferrer" class="btn-secondary">🩺 فتح بوابة الأطباء</a>
        </div>
    </div>
    <p class="page-header-desc">ربط الأطباء بالمختبرات وإنشاء حسابات دخول لبوابة الطبيب (طلبات، نتائج، حجز).</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <a href="index.php?page=admin_tenants">🏢 المختبرات</a>
        <a href="index.php?page=doctors">الأطباء المحليون (للمختبر)</a>
        <a href="index.php?page=dashboard">الرئيسية</a>
    </nav>
</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; ?>

<div class="card mb-24" id="createForm">
    <h3 class="section-title">➕ إنشاء حساب طبيب جديد</h3>
    <form method="post" action="index.php?page=admin_doctor_accounts&action=create" class="form-grid">
        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
        <input type="hidden" name="return_query" value="<?php echo htmlspecialchars($returnQuery, ENT_QUOTES, 'UTF-8'); ?>">
        <div>
            <label>المختبر (اختياري)</label>
            <select name="tenant_id" id="create_tenant_id" onchange="loadDoctors(this.value)">
                <option value="">-- بدون ربط حالياً --</option>
                <?php foreach ($tenants as $t): ?>
                <option value="<?php echo (int)$t['id']; ?>"><?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>الطبيب (اختياري)</label>
            <select name="doctor_id" id="create_doctor_id">
                <option value="">-- بدون ربط حالياً --</option>
            </select>
        </div>
        <div>
            <label>اسم المستخدم <span style="color:red;">*</span></label>
            <input type="text" name="username" required minlength="3" placeholder="للدخول للبوابة">
        </div>
        <div>
            <label>كلمة المرور <span style="color:red;">*</span></label>
            <input type="password" name="password" required minlength="6" placeholder="6 أحرف على الأقل">
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">إنشاء الحساب</button>
        </div>
    </form>
</div>

<div class="card">
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label">إجمالي الحسابات</div>
            <div class="stat-value"><?php echo (int)$stats['total']; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">الحسابات النشطة</div>
            <div class="stat-value" style="color:#16a34a;"><?php echo (int)$stats['active']; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">الحسابات المعطلة</div>
            <div class="stat-value" style="color:#dc2626;"><?php echo (int)$stats['inactive']; ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">سجّلوا دخول سابقاً</div>
            <div class="stat-value" style="color:#2563eb;"><?php echo (int)$stats['logged_in']; ?></div>
        </div>
    </div>

    <h3 class="section-title">الحسابات الحالية</h3>
    <form method="get" class="filters-form">
        <input type="hidden" name="page" value="admin_doctor_accounts">
        <div>
            <label style="display:block;margin-bottom:5px;">بحث</label>
            <input type="search" name="q" value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>" placeholder="اسم الطبيب، اسم المستخدم، الاختصاص...">
        </div>
        <div>
            <label style="display:block;margin-bottom:5px;">المختبر</label>
            <select name="tenant_id">
                <option value="0">كل المختبرات</option>
                <?php foreach ($tenants as $t): ?>
                <option value="<?php echo (int)$t['id']; ?>" <?php echo ((int)$t['id'] === $tenantFilter) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label style="display:block;margin-bottom:5px;">الحالة</label>
            <select name="status">
                <option value="" <?php echo $statusFilter === '' ? 'selected' : ''; ?>>الكل</option>
                <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>نشط</option>
                <option value="inactive" <?php echo $statusFilter === 'inactive' ? 'selected' : ''; ?>>معطل</option>
            </select>
        </div>
        <div>
            <label style="display:block;margin-bottom:5px;">ترتيب حسب</label>
            <select name="sort">
                <option value="created_at" <?php echo $sort === 'created_at' ? 'selected' : ''; ?>>تاريخ الإنشاء</option>
                <option value="doctor" <?php echo $sort === 'doctor' ? 'selected' : ''; ?>>اسم الطبيب</option>
                <option value="tenant" <?php echo $sort === 'tenant' ? 'selected' : ''; ?>>المختبر</option>
                <option value="username" <?php echo $sort === 'username' ? 'selected' : ''; ?>>اسم المستخدم</option>
                <option value="last_login" <?php echo $sort === 'last_login' ? 'selected' : ''; ?>>آخر دخول</option>
                <option value="status" <?php echo $sort === 'status' ? 'selected' : ''; ?>>الحالة</option>
            </select>
        </div>
        <div>
            <label style="display:block;margin-bottom:5px;">الاتجاه</label>
            <select name="dir">
                <option value="desc" <?php echo $dir === 'desc' ? 'selected' : ''; ?>>تنازلي</option>
                <option value="asc" <?php echo $dir === 'asc' ? 'selected' : ''; ?>>تصاعدي</option>
            </select>
        </div>
        <div>
            <label style="display:block;margin-bottom:5px;">لكل صفحة</label>
            <select name="per_page">
                <option value="10" <?php echo $perPage === 10 ? 'selected' : ''; ?>>10</option>
                <option value="20" <?php echo $perPage === 20 ? 'selected' : ''; ?>>20</option>
                <option value="50" <?php echo $perPage === 50 ? 'selected' : ''; ?>>50</option>
                <option value="100" <?php echo $perPage === 100 ? 'selected' : ''; ?>>100</option>
            </select>
        </div>
        <div style="display:flex;gap:6px;align-items:center;">
            <button type="submit" class="btn-secondary">تطبيق</button>
            <?php if ($q !== '' || $tenantFilter > 0 || $statusFilter !== ''): ?>
            <a href="index.php?page=admin_doctor_accounts" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </div>
    </form>
    <p class="results-meta">النتائج المعروضة: <?php echo count($accounts); ?> من أصل <?php echo (int)$totalRows; ?></p>
    <?php if (empty($accounts)): ?>
    <p style="color:var(--text-muted);padding:40px;text-align:center;">لا توجد حسابات أطباء. أنشئ حساباً من النموذج أعلاه.</p>
    <?php else: ?>
    <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 ($accounts as $a): ?>
            <tr>
                <td>
                    <strong><?php echo htmlspecialchars($a['doctor_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                    <?php if (!empty($a['specialty'])): ?>
                    <br><small class="doctor-meta"><?php echo htmlspecialchars($a['specialty'], ENT_QUOTES, 'UTF-8'); ?></small>
                    <?php endif; ?>
                </td>
                <td><?php echo !empty($a['tenant_name']) ? htmlspecialchars($a['tenant_name'], ENT_QUOTES, 'UTF-8') : '<span style="color:#f59e0b;">غير مرتبط</span>'; ?></td>
                <td><code><?php echo htmlspecialchars($a['username'], ENT_QUOTES, 'UTF-8'); ?></code></td>
                <td><?php echo $a['last_login_at'] ? date('Y-m-d H:i', strtotime($a['last_login_at'])) : 'لم يسجل'; ?></td>
                <td>
                    <span class="badge badge-<?php echo $a['is_active'] ? 'completed' : 'cancelled'; ?>">
                        <?php echo $a['is_active'] ? 'نشط' : 'معطل'; ?>
                    </span>
                </td>
                <td>
                    <div class="actions-cell">
                    <form method="post" action="index.php?page=admin_doctor_accounts&action=toggle&id=<?php echo (int)$a['id']; ?>" style="display:inline;">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="return_query" value="<?php echo htmlspecialchars($returnQuery, ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="is_active" value="<?php echo $a['is_active'] ? '0' : '1'; ?>">
                        <button type="submit" class="btn-secondary btn-xs">
                            <?php echo $a['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                        </button>
                    </form>
                    <button type="button" onclick="document.getElementById('reset_<?php echo (int)$a['id']; ?>').style.display='table-row'" class="btn-secondary btn-xs">تغيير كلمة المرور</button>
                    <button type="button" onclick="document.getElementById('link_<?php echo (int)$a['id']; ?>').style.display='table-row'" class="btn-secondary btn-xs">تعديل الربط</button>
                    <form method="post" action="index.php?page=admin_doctor_accounts&action=delete&id=<?php echo (int)$a['id']; ?>" style="display:inline;" onsubmit="return confirm('حذف هذا الحساب؟');">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="return_query" value="<?php echo htmlspecialchars($returnQuery, ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="btn-secondary btn-xs btn-danger-text">حذف</button>
                    </form>
                    </div>
                </td>
            </tr>
            <tr id="link_<?php echo (int)$a['id']; ?>" class="reset-row">
                <td colspan="6" class="reset-cell">
                    <form method="post" action="index.php?page=admin_doctor_accounts&action=update_link&id=<?php echo (int)$a['id']; ?>" class="reset-form">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="return_query" value="<?php echo htmlspecialchars($returnQuery, ENT_QUOTES, 'UTF-8'); ?>">
                        <label>المختبر:</label>
                        <select name="tenant_id" onchange="loadDoctorsForLink(this.value, <?php echo (int)$a['id']; ?>)" style="min-width:180px;padding:8px 10px;border-radius:8px;border:1px solid var(--border-color);">
                            <option value="">-- بدون ربط --</option>
                            <?php foreach ($tenants as $t): ?>
                            <option value="<?php echo (int)$t['id']; ?>" <?php echo ((int)($a['tenant_id'] ?? 0) === (int)$t['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <label>الطبيب:</label>
                        <select name="doctor_id" id="link_doctor_<?php echo (int)$a['id']; ?>" style="min-width:220px;padding:8px 10px;border-radius:8px;border:1px solid var(--border-color);">
                            <option value="">-- بدون ربط --</option>
                        </select>
                        <button type="submit" class="btn-primary">حفظ الربط</button>
                        <button type="button" onclick="this.closest('tr').style.display='none'">إلغاء</button>
                    </form>
                </td>
            </tr>
            <tr id="reset_<?php echo (int)$a['id']; ?>" class="reset-row">
                <td colspan="6" class="reset-cell">
                    <form method="post" action="index.php?page=admin_doctor_accounts&action=reset_password&id=<?php echo (int)$a['id']; ?>" class="reset-form">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="return_query" value="<?php echo htmlspecialchars($returnQuery, ENT_QUOTES, 'UTF-8'); ?>">
                        <label>كلمة مرور جديدة:</label>
                        <input type="password" name="new_password" required minlength="6" style="padding:8px 12px;border-radius:8px;border:1px solid var(--border-color);">
                        <button type="submit" class="btn-primary">حفظ</button>
                        <button type="button" onclick="this.closest('tr').style.display='none'">إلغاء</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if ($totalPages > 1): ?>
    <div class="pagination-wrap">
        <div class="pagination-meta">الصفحة <?php echo (int)$pageNo; ?> من <?php echo (int)$totalPages; ?></div>
        <div class="pagination-actions">
            <?php
            $pageQueryBase = [
                'page' => 'admin_doctor_accounts',
                'q' => $q !== '' ? $q : null,
                'status' => $statusFilter !== '' ? $statusFilter : null,
                'tenant_id' => $tenantFilter > 0 ? $tenantFilter : null,
                'sort' => $sort,
                'dir' => $dir,
                'per_page' => $perPage !== 20 ? $perPage : null,
            ];
            $prevQuery = http_build_query(array_merge($pageQueryBase, ['p' => max(1, $pageNo - 1)]));
            $nextQuery = http_build_query(array_merge($pageQueryBase, ['p' => min($totalPages, $pageNo + 1)]));
            $startPage = max(1, $pageNo - 2);
            $endPage = min($totalPages, $pageNo + 2);
            ?>
            <a class="btn-secondary <?php echo $pageNo <= 1 ? 'disabled' : ''; ?>" href="<?php echo $pageNo > 1 ? 'index.php?' . htmlspecialchars($prevQuery, ENT_QUOTES, 'UTF-8') : '#'; ?>">السابق</a>
            <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                <?php $numberQuery = http_build_query(array_merge($pageQueryBase, ['p' => $i])); ?>
                <a class="btn-secondary page-number <?php echo $i === $pageNo ? 'active' : ''; ?>" href="index.php?<?php echo htmlspecialchars($numberQuery, ENT_QUOTES, 'UTF-8'); ?>">
                    <?php echo (int)$i; ?>
                </a>
            <?php endfor; ?>
            <a class="btn-secondary <?php echo $pageNo >= $totalPages ? 'disabled' : ''; ?>" href="<?php echo $pageNo < $totalPages ? 'index.php?' . htmlspecialchars($nextQuery, ENT_QUOTES, 'UTF-8') : '#'; ?>">التالي</a>
        </div>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</div>
</div>

<script>
var doctorsByTenant = <?php echo json_encode($doctorsByTenant); ?>;
var accountsCurrentLinks = <?php echo json_encode(array_map(static function($acc) {
    return [
        'id' => (int)($acc['id'] ?? 0),
        'tenant_id' => (int)($acc['tenant_id'] ?? 0),
        'doctor_id' => (int)($acc['doctor_id'] ?? 0),
    ];
}, $accounts)); ?>;

function loadDoctors(tenantId) {
    var sel = document.getElementById('create_doctor_id');
    sel.innerHTML = '<option value="">-- بدون ربط حالياً --</option>';
    var tenantIdNum = parseInt(tenantId, 10);
    if (tenantIdNum && doctorsByTenant[tenantIdNum]) {
        doctorsByTenant[tenantIdNum].forEach(function(d) {
            var opt = document.createElement('option');
            opt.value = d.id;
            opt.textContent = d.full_name + (d.specialty ? ' (' + d.specialty + ')' : '');
            sel.appendChild(opt);
        });
    }
}

function loadDoctorsForLink(tenantId, accountId, selectedDoctorId) {
    var sel = document.getElementById('link_doctor_' + accountId);
    if (!sel) return;
    sel.innerHTML = '<option value="">-- بدون ربط --</option>';
    var tenantIdNum = parseInt(tenantId, 10);
    var selected = parseInt(selectedDoctorId || 0, 10);
    if (tenantIdNum && doctorsByTenant[tenantIdNum]) {
        doctorsByTenant[tenantIdNum].forEach(function(d) {
            var opt = document.createElement('option');
            opt.value = d.id;
            opt.textContent = d.full_name + (d.specialty ? ' (' + d.specialty + ')' : '');
            if (selected && parseInt(d.id, 10) === selected) opt.selected = true;
            sel.appendChild(opt);
        });
    }
}

(function initLinkRows() {
    if (!Array.isArray(accountsCurrentLinks)) return;
    accountsCurrentLinks.forEach(function(acc) {
        if (acc && acc.id) {
            loadDoctorsForLink(acc.tenant_id || 0, acc.id, acc.doctor_id || 0);
        }
    });
})();
</script>
