<?php
header('Content-Type: application/json');
header('Cache-Control: public, max-age=120');
if (!headers_sent()) {
    ob_start('ob_gzhandler');
}
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/fast.php';

$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

if ($action === 'list') {
    $cacheKey = 'departments_list';
    $cached = $fastCache->get($cacheKey);
    if ($cached !== null) {
        echo json_encode($cached);
        exit;
    }

    $sql = "SELECT id AS __backendId, dept_code, dept_name, dept_icon, dept_prefix FROM departments ORDER BY dept_name ASC";
    $data = fastQuery($sql, [], 120);

    $fastCache->set($cacheKey, $data, 120);
    echo json_encode($data);
    exit;
}

if ($action === 'create') {
    $dept_code = getSafeString('code');
    $dept_name = getSafeString('name');
    $dept_icon = getSafeString('icon', 'building-2');
    $dept_prefix = getSafeString('prefix');
    
    if (!$dept_code || !$dept_name) {
        echo json_encode(['success' => false, 'error' => 'Code and name required']);
        exit;
    }
    
    // Check if code already exists
    $check = $mysqli->prepare("SELECT id FROM departments WHERE dept_code = ?");
    $check->bind_param("s", $dept_code);
    $check->execute();
    if ($check->get_result()->num_rows > 0) {
        echo json_encode(['success' => false, 'error' => 'Department code already exists']);
        exit;
    }
    
    $stmt = $mysqli->prepare("INSERT INTO departments (dept_code, dept_name, dept_icon, dept_prefix, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->bind_param("ssss", $dept_code, $dept_name, $dept_icon, $dept_prefix);
    $ok = $stmt->execute();
    $insert_id = $stmt->insert_id;
    
    echo json_encode(['success' => $ok, 'insert_id' => $insert_id, 'dept_code' => $dept_code]);
    exit;
}

echo json_encode(['success' => false, 'error' => 'Unknown action']);
?>
