<?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 === 'delete') {
    if (!canDelete()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
    $id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
    if ($id) {
        $stmt = $conn->prepare("DELETE FROM hospitals WHERE id = ?");
        $stmt->bind_param("i", $id);
        $ok = $stmt->execute();
        if ($ok && function_exists('logActivity')) logActivity('delete', 'hospitals', $id, '');
        echo json_encode(['success' => $ok]);
    } 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'] ?? '');
    $governorate_id = (int)($_POST['governorate_id'] ?? 0);
    $phone = trim($_POST['phone'] ?? '');
    $sector = $_POST['sector'] ?? '';
    
    if (!$id || empty($name) || !$governorate_id || empty($phone) || empty($sector)) {
        echo json_encode(['success' => false, 'message' => 'جميع الحقول مطلوبة']);
        exit;
    }
    if (!preg_match('/^07\d{9}$/', $phone)) {
        echo json_encode(['success' => false, 'message' => 'رقم هاتف غير صحيح']);
        exit;
    }
    $stmt = $conn->prepare("UPDATE hospitals SET name=?, governorate_id=?, phone=?, sector=? WHERE id=?");
    $stmt->bind_param("sissi", $name, $governorate_id, $phone, $sector, $id);
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('update', 'hospitals', $id, $name);
    echo json_encode(['success' => $ok]);
    exit;
}

echo json_encode(['success' => false]);
