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

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