<?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'] ?? ''));
if ($action !== 'delete' && function_exists('require_csrf')) require_csrf();

if ($action === 'delete') {
    if (!function_exists('require_csrf')) { /* لا يوجد csrf */ }
    elseif (!empty($_GET['csrf_token']) && function_exists('csrf_verify') && !csrf_verify()) {
        echo json_encode(['success' => false, 'message' => 'انتهت صلاحية الجلسة']);
        exit;
    }
    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;
    }
    $stmt = $conn->prepare("DELETE FROM devices WHERE id = ?");
    $stmt->bind_param("i", $id);
    $ok = $stmt->execute();
    if ($ok && function_exists('logActivity')) logActivity('delete', 'devices', $id, '');
    echo json_encode(['success' => $ok]);
    exit;
}

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