<?php
// ============================================================
// AJAX Endpoint
// ============================================================
require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/helpers/functions.php';

header('Content-Type: application/json');

// Must be logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([]);
    exit;
}

$action = $_GET['action'] ?? '';
$cid    = (int)($_GET['company_id'] ?? 0);
$db     = Database::getInstance();

switch ($action) {
    case 'equipment':
        if (!$cid) { echo json_encode([]); exit; }
        $stmt = $db->prepare('SELECT equipment_id, equipment_name, model, serial_number FROM equipment WHERE company_id = ? ORDER BY equipment_name');
        $stmt->execute([$cid]);
        echo json_encode($stmt->fetchAll());
        break;

    case 'contacts':
        if (!$cid) { echo json_encode([]); exit; }
        $stmt = $db->prepare('SELECT contact_id, contact_name, position FROM contact_persons WHERE company_id = ? ORDER BY contact_name');
        $stmt->execute([$cid]);
        echo json_encode($stmt->fetchAll());
        break;

    default:
        echo json_encode([]);
}
