<?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) {
        echo json_encode(['success' => false, 'message' => 'معرف غير صالح']);
        exit;
    }
    $cnt = $conn->query("SELECT COUNT(*) c FROM devices WHERE device_name_id = $id")->fetch_assoc()['c'];
    if ($cnt > 0) {
        echo json_encode(['success' => false, 'message' => 'لا يمكن الحذف: اسم الجهاز مرتبط بـ ' . $cnt . ' جهاز']);
        exit;
    }
    $stmt = $conn->prepare("DELETE FROM device_names WHERE id = ?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('delete', 'device_names', $id, '');
    echo json_encode(['success' => $ok]);
    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'] ?? '');
    if (!$id || empty($name)) {
        echo json_encode(['success' => false, 'message' => 'الاسم مطلوب']);
        exit;
    }
    $stmt = $conn->prepare("UPDATE device_names SET name = ? WHERE id = ?");
    $stmt->bind_param("si", $name, $id);
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('update', 'device_names', $id, $name);
    echo json_encode(['success' => $ok, 'message' => $stmt->error ? 'الاسم قد يكون مكرراً' : '']);
    exit;
}

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