<?php
declare(strict_types=1);
session_start();
date_default_timezone_set('America/Guayaquil');
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['ingreso']) || $_SESSION['ingreso'] !== 'YES') {
  http_response_code(401);
  echo json_encode(['draw'=>0,'recordsTotal'=>0,'recordsFiltered'=>0,'data'=>[],'error'=>'No autorizado']); exit;
}

require_once __DIR__ . '/../conex.php';
if (!isset($conn) || !$conn instanceof mysqli) {
  http_response_code(500);
  echo json_encode(['draw'=>0,'recordsTotal'=>0,'recordsFiltered'=>0,'data'=>[],'error'=>'Sin conexión a BD']); exit;
}
mysqli_set_charset($conn, 'utf8mb4');
if (function_exists('mysqli_report')) { mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); }

$req   = $_GET + $_POST;
$draw  = (int)($req['draw'] ?? 0);
$start = max(0,(int)($req['start'] ?? 0));
$length= (int)($req['length'] ?? 10);
if ($length < 1 || $length > 500) $length = 10;
$searchValue = trim((string)($req['search']['value'] ?? ''));

$columns = [
  0 => 'ruc',
  1 => 'razon_social',
  2 => 'alias',
  3 => 'servicios',
  4 => 'estado',
  5 => 'idempresa',
];

$orderBy = 'idempresa DESC';
if (isset($req['order'][0]['column'], $req['order'][0]['dir'])) {
  $colIdx = (int)$req['order'][0]['column'];
  $dir    = strtolower($req['order'][0]['dir']) === 'asc' ? 'ASC' : 'DESC';
  if (isset($columns[$colIdx]) && $colIdx !== 5) $orderBy = $columns[$colIdx].' '.$dir;
}

/* Totales solo con condicion=1 */
$res = $conn->query("SELECT COUNT(*) AS c FROM tb_empresa WHERE condicion=1");
$totalRecords = (int)$res->fetch_assoc()['c'];
$res->close();

/* Filtro */
$where = ' WHERE condicion=1';
$params = []; $types = '';
if ($searchValue !== '') {
  $where .= " AND (ruc LIKE ? OR razon_social LIKE ? OR alias LIKE ? OR CAST(servicios AS CHAR) LIKE ?)";
  $sv = "%$searchValue%";
  $params = [$sv, $sv, $sv, $sv];
  $types  = 'ssss';
}

/* Total filtrado */
if ($searchValue !== '') {
  $stmt = $conn->prepare("SELECT COUNT(*) AS c FROM tb_empresa $where");
  $stmt->bind_param($types, ...$params);
  $stmt->execute(); $stmt->bind_result($filtered); $stmt->fetch(); $stmt->close();
  $recordsFiltered = (int)$filtered;
} else {
  $recordsFiltered = $totalRecords;
}

/* Datos */
$sql = "SELECT idempresa, ruc, razon_social, alias, servicios, estado
        FROM tb_empresa
        $where
        ORDER BY $orderBy
        LIMIT ?, ?";
if ($searchValue !== '') {
  $stmt = $conn->prepare($sql);
  $params[] = $start; $params[] = $length; $types .= 'ii';
  $stmt->bind_param($types, ...$params);
} else {
  $stmt = $conn->prepare($sql);
  $stmt->bind_param('ii', $start, $length);
}
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($r = $result->fetch_assoc()) {
  $data[] = [
    'ruc'          => $r['ruc'],
    'razon_social' => $r['razon_social'],
    'alias'        => $r['alias'],
    'servicios'    => (int)$r['servicios'],
    'estado'       => (int)$r['estado'],
    'idempresa'    => (int)$r['idempresa'],
  ];
}
$stmt->close();

echo json_encode([
  'draw'=>$draw,
  'recordsTotal'=>$totalRecords,
  'recordsFiltered'=>$recordsFiltered,
  'data'=>$data
], JSON_UNESCAPED_UNICODE);
