<?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 === 'companies' || isset($_GET['companies'])) && isset($_GET['device_name_id'])) {
    $dn = (int)($_GET['device_name_id'] ?? 0);
    if ($dn) {
        $st = $conn->prepare("SELECT DISTINCT c.id, c.name FROM companies c JOIN device_models dm ON dm.company_id = c.id WHERE dm.device_name_id = ? ORDER BY c.name");
        $st->bind_param("i", $dn);
        $st->execute();
        $r = $st->get_result();
        $rows = [];
        while ($row = $r->fetch_assoc()) $rows[] = $row;
        echo json_encode(['success' => true, 'data' => $rows]);
    } else {
        echo json_encode(['success' => true, 'data' => []]);
    }
    exit;
}

if (($action === 'list' || isset($_GET['device_name_id'])) && isset($_GET['company_id'])) {
    $dn = (int)($_GET['device_name_id'] ?? 0);
    $co = (int)($_GET['company_id'] ?? 0);
    if ($dn && $co) {
        $st = $conn->prepare("SELECT id, model_name FROM device_models WHERE device_name_id=? AND company_id=? ORDER BY model_name");
        $st->bind_param("ii", $dn, $co);
        $st->execute();
        $r = $st->get_result();
        $rows = [];
        while ($row = $r->fetch_assoc()) $rows[] = $row;
        echo json_encode(['success' => true, 'data' => $rows]);
    } else {
        echo json_encode(['success' => true, 'data' => []]);
    }
    exit;
}

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

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