<?php
require_once(__DIR__ . '/../db/conexion.php');
header('Content-Type: application/json');

$sql = "SELECT Sector, Tiendas FROM sectoresdPDVs ORDER BY Sector ASC";
$result = $conn->query($sql);

$data = [];

if ($result) {
  while ($row = $result->fetch_assoc()) {
    $sector = trim($row['Sector']);
    $sector = $sector !== '' ? $sector : 'Sin Sector';

    $tiendas = array_filter(array_map(function($t) {
        $t = trim($t);
        return $t !== '' ? $t : 'SIN PDV';
    }, explode(',', $row['Tiendas'])));

    $data[] = [
      'nombre' => $sector,
      'pdvs' => $tiendas
    ];
  }

  echo json_encode(['success' => true, 'data' => $data]);
} else {
  echo json_encode(['success' => false, 'message' => 'Error en la consulta']);
}
