<?php
/**
 * لوحة Super Admin - إدارة حسابات الأطباء وربطهم بالمختبرات
 * إنشاء حسابات دخول للأطباء للوصول إلى بوابة Smart Doctor
 */
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);

// إنشاء الجداول إن لم تكن موجودة
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) {} }
}

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

    $err = '';
    if ($tenantIdSel <= 0) $err = 'اختر المختبر.';
    elseif ($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 {
                $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'] = 'هذا الطبيب لديه حساب مسبقاً في هذا المختبر.';
                    } else {
                        $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, $tenantIdSel, $username, $hash, $_SESSION['user_id'] ?? null]);
                        $_SESSION['doctor_acc_msg'] = 'تم إنشاء الحساب بنجاح.';
                        if (isset($auditLog)) {
                            $auditLog->log('doctor_account_created', 'doctor_account', (int)$db->lastInsertId(), null, json_encode(['username' => $username, 'doctor_id' => $doctorIdSel, 'tenant_id' => $tenantIdSel], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                        }
                    }
                }
            }
        } catch (Throwable $e) {
            $_SESSION['doctor_acc_error'] = 'خطأ: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=admin_doctor_accounts');
    exit;
}

// تعديل / تفعيل / تعطيل
if ($action === 'toggle' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $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'] = 'فشل التحديث.';
    }
    header('Location: index.php?page=admin_doctor_accounts');
    exit;
}

// إعادة تعيين كلمة المرور
if ($action === 'reset_password' && $editId > 0 && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $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 أحرف على الأقل.';
    }
    header('Location: index.php?page=admin_doctor_accounts');
    exit;
}

// حذف
if ($action === 'delete' && $editId > 0) {
    try {
        $db->prepare('DELETE FROM doctor_accounts WHERE id = ?')->execute([$editId]);
        $_SESSION['doctor_acc_msg'] = 'تم حذف الحساب.';
    } catch (Throwable $e) {
        $_SESSION['doctor_acc_error'] = 'فشل الحذف.';
    }
    header('Location: index.php?page=admin_doctor_accounts');
    exit;
}

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

$accounts = [];
try {
    $stmt = $db->query('SELECT da.*, d.full_name AS doctor_name, d.specialty, d.clinic_name, t.name AS tenant_name, t.slug AS tenant_slug
                        FROM doctor_accounts da
                        JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id
                        JOIN tenants t ON t.id = da.tenant_id
                        ORDER BY da.created_at DESC');
    $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';
?>
<div class="page-header">
    <h1>إدارة حسابات الأطباء</h1>
    <p style="color:var(--text-muted);margin-top:4px;">ربط الأطباء بالمختبرات وإنشاء حسابات دخول لبوابة Smart Doctor</p>
    <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" class="btn-secondary">🩺 فتح بوابة الأطباء</a>
    </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; ?>

<div class="card" id="createForm" style="margin-bottom:24px;">
    <h3 style="margin-top:0;">➕ إنشاء حساب طبيب جديد</h3>
    <form method="post" action="index.php?page=admin_doctor_accounts&action=create" class="form-grid">
        <div>
            <label>المختبر <span style="color:red;">*</span></label>
            <select name="tenant_id" id="create_tenant_id" required 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>الطبيب <span style="color:red;">*</span></label>
            <select name="doctor_id" id="create_doctor_id" required>
                <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">
    <h3 style="margin-top:0;">الحسابات الحالية</h3>
    <?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 style="color:var(--text-muted);"><?php echo htmlspecialchars($a['specialty'], ENT_QUOTES, 'UTF-8'); ?></small>
                    <?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($a['tenant_name'], ENT_QUOTES, 'UTF-8'); ?></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>
                    <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="is_active" value="<?php echo $a['is_active'] ? '0' : '1'; ?>">
                        <button type="submit" class="btn-secondary" style="padding:4px 10px;font-size:12px;">
                            <?php echo $a['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                        </button>
                    </form>
                    <button type="button" onclick="document.getElementById('reset_<?php echo (int)$a['id']; ?>').style.display='block'" class="btn-secondary" style="padding:4px 10px;font-size:12px;">تغيير كلمة المرور</button>
                    <a href="index.php?page=admin_doctor_accounts&action=delete&id=<?php echo (int)$a['id']; ?>" class="btn-secondary" style="padding:4px 10px;font-size:12px;color:#ef4444;" onclick="return confirm('حذف هذا الحساب؟');">حذف</a>
                </td>
            </tr>
            <tr id="reset_<?php echo (int)$a['id']; ?>" style="display:none;background:var(--bg-secondary);">
                <td colspan="6" style="padding:16px;">
                    <form method="post" action="index.php?page=admin_doctor_accounts&action=reset_password&id=<?php echo (int)$a['id']; ?>" style="display:flex;gap:12px;align-items:center;">
                        <label>كلمة مرور جديدة:</label>
                        <input type="password" name="new_password" required minlength="6" style="padding:6px 12px;">
                        <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 endif; ?>
</div>

<script>
var doctorsByTenant = <?php echo json_encode($doctorsByTenant); ?>;

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);
        });
    }
}
</script>
