<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';

require_login();
header('Content-Type: application/json; charset=utf-8');
if (current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No autorizado.'));
    exit;
}

try {
    $pdo = db();
    $rows = $pdo->query("SELECT fc.id, fc.center_code, fc.center_name, fc.center_type, fc.parent_id,
                               fc.is_default, fc.is_active, fc.description, fc.created_at, fc.updated_at,
                               parent.center_name AS parent_name,
                               CASE WHEN fc.center_code IN ('NO_INCOME_CENTER','NO_COST_CENTER') THEN 1 ELSE 0 END AS is_system,
                               (SELECT COUNT(*) FROM crm_customers c WHERE c.default_income_center_id = fc.id OR c.default_cost_center_id = fc.id OR c.supplier_default_cost_center_id = fc.id) AS counterparties_count,
                               (SELECT COUNT(*) FROM crm_documents d WHERE d.finance_center_id = fc.id) AS issued_documents_count,
                               (SELECT COUNT(*) FROM facto_inbox_documents i WHERE i.finance_center_id = fc.id) AS received_documents_count,
                               ((SELECT COUNT(*) FROM cost_categories cc WHERE cc.default_finance_center_id = fc.id) +
                                (SELECT COUNT(*) FROM cost_entries ce WHERE ce.finance_center_id = fc.id) +
                                (SELECT COUNT(*) FROM cost_allocations ca WHERE ca.finance_center_id = fc.id) +
                                (SELECT COUNT(*) FROM cost_recurring_rules cr WHERE cr.finance_center_id = fc.id) +
                                (SELECT COUNT(*) FROM cost_payroll_entries cp WHERE cp.finance_center_id = fc.id)) AS costs_count,
                               (SELECT COUNT(*) FROM billing_collections bc WHERE bc.finance_center_id = fc.id) AS collections_count
                        FROM finance_centers fc
                        LEFT JOIN finance_centers parent ON parent.id = fc.parent_id
                        ORDER BY fc.is_active DESC, fc.center_type, fc.is_default DESC, fc.center_name")->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(array('success' => true, 'data' => $rows), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
