<?php
/**
 * سكريبت تشخيصي لاختبار إنشاء مستشفى
 * يستخدم لإيجاد سبب فشل الحفظ - احذف هذا الملف بعد التشخيص
 */
require_once __DIR__ . '/../auth.php';
requireLogin();
require_once __DIR__ . '/../config.php';

header('Content-Type: application/json; charset=utf-8');

$result = ['success' => false, 'checks' => [], 'error' => null];

// 1. التحقق من الصلاحيات
$result['checks']['can_edit'] = canEdit();

// 2. التحقق من وجود الجداول والأعمدة
$tables = ['hospitals', 'governorates', 'sectors'];
foreach ($tables as $t) {
    $r = @$conn->query("SHOW TABLES LIKE '$t'");
    $result['checks']["table_$t"] = ($r && $r->num_rows > 0);
}

// 3. التحقق من عمود responsible_person
$r = @$conn->query("SHOW COLUMNS FROM hospitals LIKE 'responsible_person'");
$result['checks']['has_responsible_person'] = ($r && $r->num_rows > 0);

// 4. اختبار إدراج تجريبي (مع حذف فوري)
$test_name = 'اختبار_حذفني_' . time();
$test_phone = '07900000000';
$gov_id = (int)($conn->query("SELECT id FROM governorates LIMIT 1")->fetch_assoc()['id'] ?? 0);
$result['checks']['governorate_exists'] = ($gov_id > 0);

if ($gov_id > 0) {
    $has_resp = ($r = @$conn->query("SHOW COLUMNS FROM hospitals LIKE 'responsible_person'")) && $r->num_rows > 0;
    $sector = 'حكومي';
    if ($has_resp) {
        $resp = '';
        $stmt = $conn->prepare("INSERT INTO hospitals (name, responsible_person, governorate_id, phone, sector) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("ssiss", $test_name, $resp, $gov_id, $test_phone, $sector);
    } else {
        $stmt = $conn->prepare("INSERT INTO hospitals (name, governorate_id, phone, sector) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("siss", $test_name, $gov_id, $test_phone, $sector);
    }
    if ($stmt) {
        $ok = $stmt->execute();
        $result['checks']['insert_test'] = $ok;
        $result['checks']['insert_error'] = $ok ? null : ($stmt->error ?? $conn->error);
        if ($ok) {
            $id = $conn->insert_id;
            $conn->query("DELETE FROM hospitals WHERE id = " . (int)$id);
        }
    } else {
        $result['checks']['insert_test'] = false;
        $result['checks']['insert_error'] = $conn->error ?? 'فشل prepare';
    }
}

$result['success'] = !empty($result['checks']['insert_test']);
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
