<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();
header('Content-Type: application/json');

$mysqli = db();
$action = $_GET['action'] ?? $_POST['action'] ?? 'list';

// Ensure cost_centers table exists
$mysqli->query("CREATE TABLE IF NOT EXISTS cost_centers (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    name        VARCHAR(150) NOT NULL UNIQUE,
    description VARCHAR(255) DEFAULT NULL,
    is_active   TINYINT(1)   NOT NULL DEFAULT 1,
    created_at  TIMESTAMP    DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB");

// Seed from branches + standard defaults if empty
$cnt = $mysqli->query("SELECT COUNT(*) c FROM cost_centers")->fetch_assoc()['c'];
if ((int)$cnt === 0) {
    $seeds = ['Head Office', 'Administration', 'Production', 'Sales & Marketing', 'Warehouse'];
    $ins = $mysqli->prepare("INSERT IGNORE INTO cost_centers (name) VALUES (?)");
    foreach ($seeds as $s) { $ins->bind_param('s', $s); $ins->execute(); }
    $ins->close();

    // Also seed from branches table
    $br = $mysqli->query("SELECT name FROM branches WHERE is_active=1");
    if ($br) {
        $ins2 = $mysqli->prepare("INSERT IGNORE INTO cost_centers (name) VALUES (?)");
        while ($row = $br->fetch_assoc()) { $ins2->bind_param('s', $row['name']); $ins2->execute(); }
        $ins2->close();
    }
}

switch ($action) {

    case 'list':
        $activeOnly = isset($_GET['active_only']) ? (int)$_GET['active_only'] : 1;
        $where = $activeOnly ? 'WHERE is_active=1' : '';
        $res = $mysqli->query("SELECT id, name, description, is_active FROM cost_centers $where ORDER BY name");
        $data = [];
        while ($row = $res->fetch_assoc()) $data[] = $row;
        json_response(['data' => $data]);
        break;

    case 'create':
        if (!has_role(['admin','super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $name = trim($_POST['name'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        if ($name === '') json_response(['message' => 'Name is required'], 400);
        $stmt = $mysqli->prepare("INSERT INTO cost_centers (name, description) VALUES (?, ?)");
        $stmt->bind_param('ss', $name, $desc);
        if (!$stmt->execute()) json_response(['message' => 'Duplicate or DB error: ' . $stmt->error], 500);
        json_response(['success' => true, 'id' => $mysqli->insert_id, 'message' => 'Cost center created']);
        break;

    case 'update':
        if (!has_role(['admin','super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $id     = (int)($_POST['id'] ?? 0);
        $name   = trim($_POST['name'] ?? '');
        $desc   = trim($_POST['description'] ?? '');
        $active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;
        if (!$id || $name === '') json_response(['message' => 'ID and name required'], 400);
        $stmt = $mysqli->prepare("UPDATE cost_centers SET name=?, description=?, is_active=? WHERE id=?");
        $stmt->bind_param('ssii', $name, $desc, $active, $id);
        if (!$stmt->execute()) json_response(['message' => 'Update failed: ' . $stmt->error], 500);
        json_response(['success' => true, 'message' => 'Updated']);
        break;

    case 'delete':
        if (!has_role(['admin','super_admin'])) json_response(['message' => 'Access denied'], 403);
        if (!validate_csrf($_POST['csrf'] ?? '')) json_response(['message' => 'Invalid CSRF'], 400);
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) json_response(['message' => 'ID required'], 400);
        $stmt = $mysqli->prepare("DELETE FROM cost_centers WHERE id=?");
        $stmt->bind_param('i', $id);
        if (!$stmt->execute()) json_response(['message' => 'Delete failed'], 500);
        json_response(['success' => true, 'message' => 'Deleted']);
        break;

    default:
        json_response(['message' => 'Unknown action'], 400);
}
