<?php
require_once __DIR__ . '/../auth.php';
requireLogin();
require_once __DIR__ . '/../config.php';
if (function_exists('require_csrf')) require_csrf();

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

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'list') {
    $r = $conn->query("SELECT s.*, 
        (SELECT COUNT(*) FROM hospitals WHERE sector = s.name) as hospital_count,
        (SELECT COUNT(*) FROM clinics WHERE sector = s.name) as clinic_count
        FROM sectors s ORDER BY s.name");
    if (!$r) $r = $conn->query("SELECT s.*, 0 as hospital_count, 0 as clinic_count FROM sectors s ORDER BY s.name");
    $rows = [];
    while ($row = $r->fetch_assoc()) $rows[] = $row;
    echo json_encode(['success' => true, 'data' => $rows]);
    exit;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!canEdit()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
    $name = trim($_POST['name'] ?? '');
    $for_hospitals = isset($_POST['for_hospitals']) ? (int)$_POST['for_hospitals'] : 1;
    $for_clinics = isset($_POST['for_clinics']) ? (int)$_POST['for_clinics'] : 1;
    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => 'اسم القطاع مطلوب']);
        exit;
    }
    $hasCols = @$conn->query("SHOW COLUMNS FROM sectors LIKE 'for_hospitals'")->num_rows > 0;
    if ($hasCols) {
        $stmt = $conn->prepare("INSERT INTO sectors (name, for_hospitals, for_clinics) VALUES (?, ?, ?)");
        $stmt->bind_param("sii", $name, $for_hospitals, $for_clinics);
    } else {
        $stmt = $conn->prepare("INSERT INTO sectors (name) VALUES (?)");
        $stmt->bind_param("s", $name);
    }
    if ($stmt->execute()) {
        if (function_exists('logActivity')) logActivity('add', 'sectors', $conn->insert_id, $name);
        echo json_encode(['success' => true, 'id' => $conn->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'الاسم موجود مسبقاً']);
    }
    exit;
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!canEdit()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
    $id = (int)($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $for_hospitals = isset($_POST['for_hospitals']) ? (int)$_POST['for_hospitals'] : null;
    $for_clinics = isset($_POST['for_clinics']) ? (int)$_POST['for_clinics'] : null;
    if (!$id || empty($name)) {
        echo json_encode(['success' => false, 'message' => 'معرف واسم القطاع مطلوبان']);
        exit;
    }
    $stmt = $conn->prepare("SELECT name FROM sectors WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    if (!$row) { echo json_encode(['success' => false, 'message' => 'القطاع غير موجود']); exit; }
    $oldName = $row['name'];
    $hasCols = @$conn->query("SHOW COLUMNS FROM sectors LIKE 'for_hospitals'")->num_rows > 0;
    if ($hasCols && $for_hospitals !== null && $for_clinics !== null) {
        $st2 = $conn->prepare("UPDATE sectors SET name=?, for_hospitals=?, for_clinics=? WHERE id=?");
        $st2->bind_param("siii", $name, $for_hospitals, $for_clinics, $id);
    } else {
        $st2 = $conn->prepare("UPDATE sectors SET name=? WHERE id=?");
        $st2->bind_param("si", $name, $id);
    }
    if (!$st2->execute()) {
        echo json_encode(['success' => false, 'message' => 'الاسم موجود مسبقاً']);
        exit;
    }
    if (function_exists('logActivity')) logActivity('update', 'sectors', $id, $name);
    if ($oldName !== $name) {
        $st3 = $conn->prepare("UPDATE hospitals SET sector=? WHERE sector=?");
        $st3->bind_param("ss", $name, $oldName);
        $st3->execute();
        $st4 = $conn->prepare("UPDATE clinics SET sector=? WHERE sector=?");
        $st4->bind_param("ss", $name, $oldName);
        $st4->execute();
    }
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!canDelete()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['success' => false, 'message' => 'معرف غير صالح']); exit; }
    $stmt = $conn->prepare("SELECT name FROM sectors WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    if (!$row) { echo json_encode(['success' => false, 'message' => 'القطاع غير موجود']); exit; }
    $st2 = $conn->prepare("SELECT (SELECT COUNT(*) FROM hospitals WHERE sector=?) + (SELECT COUNT(*) FROM clinics WHERE sector=?) as c");
    $st2->bind_param("ss", $row['name'], $row['name']);
    $st2->execute();
    $cnt = $st2->get_result()->fetch_assoc()['c'];
    if ($cnt > 0) {
        echo json_encode(['success' => false, 'message' => "لا يمكن الحذف: مستخدم في $cnt جهة (مستشفى/عيادة)"]);
        exit;
    }
    $st3 = $conn->prepare("DELETE FROM sectors WHERE id=?");
    $st3->bind_param("i", $id);
    $ok = $st3->execute();
    if ($ok && function_exists('logActivity')) logActivity('delete', 'sectors', $id, $row['name']);
    echo json_encode(['success' => $ok]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'إجراء غير صالح']);
