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

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

$action = trim((string)($_GET['action'] ?? $_POST['action'] ?? ''));
$hospital_id_param = (int)($_GET['hospital_id'] ?? $_POST['hospital_id'] ?? 0);
// إذا وُجد hospital_id فالطلب واضح - معالجة لمشكلة فقدان action في بعض السيرفرات
if ($hospital_id_param > 0) {
    $action = 'get_or_create_from_hospital';
}
if ($action !== 'list' && $action !== 'get_or_create_from_hospital' && $action !== 'create' && function_exists('require_csrf')) {
    require_csrf();
}

if ($action === 'list') {
    $search = $_GET['q'] ?? '';
    $stmt = $conn->prepare("SELECT c.*, g.name_ar as gov_name FROM customers c 
        LEFT JOIN governorates g ON c.governorate_id = g.id 
        WHERE c.name LIKE ? ORDER BY c.name");
    $s = "%$search%";
    $stmt->bind_param("s", $s);
    $stmt->execute();
    $r = $stmt->get_result();
    $rows = [];
    while ($row = $r->fetch_assoc()) $rows[] = $row;
    echo json_encode(['success' => true, 'data' => $rows]);
    exit;
}

if ($action === 'get_or_create_from_hospital') {
    $hospital_id = (int)($_GET['hospital_id'] ?? $_POST['hospital_id'] ?? 0);
    if (!$hospital_id) { echo json_encode(['success' => false, 'message' => 'معرف المستشفى مطلوب']); exit; }
    $st0 = $conn->prepare("SELECT name, phone, governorate_id FROM hospitals WHERE id = ?");
    $st0->bind_param("i", $hospital_id);
    $st0->execute();
    $h = $st0->get_result()->fetch_assoc();
    if (!$h) { echo json_encode(['success' => false, 'message' => 'المستشفى غير موجود']); exit; }
    $name = trim($h['name']);
    $stmt = $conn->prepare("SELECT id FROM customers WHERE name = ? AND (hospital_name = ? OR hospital_name IS NULL) LIMIT 1");
    $stmt->bind_param("ss", $name, $name);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    if ($row) {
        echo json_encode(['success' => true, 'id' => $row['id'], 'name' => $name, 'hospital_name' => $name, 'phone' => $h['phone'], 'governorate_id' => $h['governorate_id']]);
    } else {
        if (!canEdit()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
        $st2 = $conn->prepare("INSERT INTO customers (name, hospital_name, phone, governorate_id) VALUES (?, ?, ?, ?)");
        $st2->bind_param("sssi", $name, $name, $h['phone'], $h['governorate_id']);
        if ($st2->execute()) {
            if (function_exists('logActivity')) logActivity('add', 'customers', $conn->insert_id, $name . ' (من المستشفى)');
            echo json_encode(['success' => true, 'id' => $conn->insert_id, 'name' => $name, 'hospital_name' => $name, 'phone' => $h['phone'], 'governorate_id' => $h['governorate_id']]);
        } else {
            echo json_encode(['success' => false, 'message' => 'فشل إنشاء الزبون']);
        }
    }
    exit;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!canEdit()) { echo json_encode(['success' => false, 'message' => 'غير مسموح']); exit; }
    $name = trim($_POST['name'] ?? '');
    $hospital_name = trim($_POST['hospital_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $governorate_id = (int)($_POST['governorate_id'] ?? 0) ?: null;
    
    if (empty($name)) {
        echo json_encode(['success' => false, 'message' => 'اسم الزبون مطلوب']);
        exit;
    }
    $stmt = $conn->prepare("INSERT INTO customers (name, hospital_name, phone, governorate_id) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("sssi", $name, $hospital_name, $phone, $governorate_id);
    if ($stmt->execute()) {
        if (function_exists('logActivity')) logActivity('add', 'customers', $conn->insert_id, $name);
        echo json_encode(['success' => true, 'id' => $conn->insert_id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'فشل الحفظ']);
    }
    exit;
}

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