    <?php
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
    require_once __DIR__ . '/../includes/session_control.php';
    require_once __DIR__ . '/../cotizaciones/api/_node.php';
    require_once __DIR__ . '/../includes/user_activity_log.php';

    $token = cpn_node_token_or_fail();
    $base = cpn_node_api_base();

    // → CREAR NUEVO PEDIDO
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
        $fecha = (string)($_POST['fecha'] ?? '');
        $idProveedorArea = (int)($_POST['idProveedorArea'] ?? 0);
        $idEmpresa = (int)($_POST['idEmpresa'] ?? 0);

        $payload = [
            'fecha' => $fecha,
            'idProveedorArea' => $idProveedorArea,
            'idEmpresa' => $idEmpresa,
        ];

        $r = cpn_node_request('POST', $base . '/api/ordenes/pedidos', $token, $payload);
        if (!isset($r['ok']) || $r['ok'] !== true) {
            http_response_code($r['_http'] ?? 500);
            die('Error creando pedido en Node');
        }

        $newId = (int)($r['data']['id'] ?? 0);
        if (!$newId) {
            http_response_code(500);
            die('Error creando pedido: respuesta inválida');
        }

        cpn_activity_log_event(
            'Compras',
            'compras.pedido_create',
            'Creó el pedido #' . $newId,
            'pedido',
            $newId
        );

        header("Location: pedido.php?id=$newId");
        exit;
    }

    // → FUNCIONES AUXILIARES
    function fmt($val)
    {
        if ($val == 0) return '-';
        return '$ ' . number_format(abs($val), 0, '', '.');
    }
    function getTextColor(string $hex): string
    {
        $h = ltrim($hex, '#');
        $r = hexdec(substr($h, 0, 2));
        $g = hexdec(substr($h, 2, 2));
        $b = hexdec(substr($h, 4, 2));
        $lum = ($r * 0.299 + $g * 0.587 + $b * 0.114) / 255;
        return $lum > 0.5 ? '#000000' : '#ffffff';
    }

    // → PAGINACIÓN
    $page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit  = 50;
    $offset = ($page - 1) * $limit;

    // → FILTROS
    $filter_id        = isset($_GET['filter_id']) && $_GET['filter_id'] !== ''
        ? intval($_GET['filter_id']) : '';
    $filter_factura   = trim((string)($_GET['filter_factura'] ?? ''));
    $filter_proveedor = isset($_GET['filter_proveedor']) && $_GET['filter_proveedor'] !== '0'
        ? intval($_GET['filter_proveedor']) : '';
    // --- Añade filtro por Estado de Pedido ---
    $filter_estado = isset($_GET['filter_estado']) && $_GET['filter_estado'] !== '0'
        ? intval($_GET['filter_estado']) : '';

    // → Cargar datos desde Node
    $listUrl = $base . '/api/ordenes/pedidos?' . http_build_query([
        'page' => $page,
        'limit' => $limit,
        'filter_id' => $filter_id !== '' ? (int)$filter_id : null,
        'filter_factura' => $filter_factura,
        'filter_proveedor' => $filter_proveedor !== '' ? (int)$filter_proveedor : null,
        'filter_estado' => $filter_estado !== '' ? (int)$filter_estado : null,
    ]);
    $resp = cpn_node_request('GET', $listUrl, $token);
    if (!isset($resp['ok']) || $resp['ok'] !== true) {
        http_response_code($resp['_http'] ?? 500);
        die('Error consultando pedidos en Node');
    }

    $items = $resp['data']['items'] ?? [];
    $totalPages = (int)($resp['data']['totalPages'] ?? 1);

    $metaResp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/meta', $token);
    if (!isset($metaResp['ok']) || $metaResp['ok'] !== true) {
        http_response_code($metaResp['_http'] ?? 500);
        die('Error consultando meta de pedidos en Node');
    }

    $meta = $metaResp['data'] ?? [];
    $proveedores = $meta['proveedores'] ?? [];
    $estados = $meta['estados'] ?? [];
    $empresas = $meta['empresas'] ?? [];
    $proveedoresAreas = $meta['proveedoresAreas'] ?? [];

    // → CONSULTA “Pedidos por Reclamar”
    $reclamarSql = "
SELECT 
  oc.idEstadoOrden,
  p.nombre      AS Proveedor,
  pa.nombreArea AS Area,
  oc.fechaSolicitud,
  oc.id         AS idOrden,
  pa.idProveedor,
  oc.idProveedorArea,
  pv.referenciaCPN,
  pv.referenciaProveedor,
  pr.nombre     AS nombre,
  pv.txtColor,
  iv.linkImagen,
  od.cantidad,
  od.precioCompra,
  od.porcentajeImpuesto
FROM tb_ordenes_de_compra oc
INNER JOIN tb_proveedores_areas pa ON oc.idProveedorArea = pa.id
INNER JOIN tb_proveedores p       ON pa.idProveedor      = p.id
INNER JOIN tb_ordenes_de_compra_detalle od ON oc.id = od.idOrden
INNER JOIN tb_productos_variantes pv      ON od.idProductoVariante = pv.id
INNER JOIN tb_productos pr                ON pv.idProducto          = pr.id
LEFT  JOIN tb_imagenes_variantes iv       ON pv.id                  = iv.idVariante
WHERE oc.idEstadoOrden = 2
  AND pa.idProveedor   <> 8
ORDER BY oc.fechaSolicitud
";
    $reclamarResp = cpn_node_request('GET', $base . '/api/ordenes/pedidos/reclamar', $token);
    $reclamarRows = (isset($reclamarResp['ok']) && $reclamarResp['ok'] === true) ? ($reclamarResp['data'] ?? []) : [];
    $reclamarData = [];
    foreach ($reclamarRows as $row) {
        $prov = (string)($row['Proveedor'] ?? '');
        $area = (string)($row['Area'] ?? '');
        $key = $prov . ($area ? " ({$area})" : '');
        $idOrden = (int)($row['idOrden'] ?? 0);
        if (!$idOrden) continue;
        $reclamarData[$key][$idOrden][] = $row;
    }

    ?>
    <?php include '../templates/header.php'; ?>
    <style>
        /* Compacto (solo esta pantalla) */
        #content .container-fluid .table {
            font-size: 12px;
        }

        #content .container-fluid .table th,
        #content .container-fluid .table td {
            padding: .25rem .35rem;
            line-height: 1.15;
        }

        #content .container-fluid .form-control,
        #content .container-fluid .custom-select,
        #content .container-fluid .form-select {
            font-size: 12px !important;
            padding: .2rem .4rem;
            height: calc(1.2em + .5rem + 2px);
        }

        #content .container-fluid .btn {
            font-size: 12px;
            padding: .25rem .5rem;
        }

        #content .container-fluid h1.h3,
        #content .container-fluid .h3 {
            font-size: 1.1rem;
        }

        #content .container-fluid .pagination .page-link {
            font-size: 12px;
            padding: .25rem .5rem;
        }
    </style>
    <h1 class="h3 mb-4 text-gray-800">Pedidos de Compra</h1>
    <a href="pedidos.php" class="btn btn-secondary mb-2">Limpiar</a>
    <button class="btn btn-success mb-2" data-bs-toggle="modal" data-bs-target="#newOrderModal">
        Crear Nuevo Pedido
    </button>
    <button class="btn btn-warning mb-2 ms-2" data-bs-toggle="modal" data-bs-target="#reclamarModal">
        Pedidos por Reclamar
    </button>


    <!-- FILTROS -->
    <form class="form-inline mb-3" method="get">
        <input type="text" name="filter_id" class="form-control mr-2 mb-2" placeholder="No."
            value="<?= htmlspecialchars($filter_id) ?>">
        <input type="text" name="filter_factura" class="form-control mr-2 mb-2" placeholder="Factura"
            value="<?= htmlspecialchars($filter_factura) ?>">
        <select name="filter_proveedor" class="form-control mr-2 mb-2">
            <option value="0">Todos los Proveedores</option>
            <?php foreach ($proveedores as $p):
                $pid = (int)($p['id'] ?? 0);
                $sel = ($filter_proveedor !== '' && (int)$filter_proveedor === $pid) ? 'selected' : '';
            ?>
                <option value="<?= $pid ?>" <?= $sel ?>><?= htmlspecialchars((string)($p['nombre'] ?? '')) ?></option>
            <?php endforeach; ?>
        </select>
        <!-- Filtro por Estado -->
        <select name="filter_estado" class="form-control mr-2 mb-2">
            <option value="0">Todos los Estados</option>
            <?php foreach ($estados as $e):
                $eid = (int)($e['id'] ?? 0);
                $sel = ($filter_estado !== '' && (int)$filter_estado === $eid) ? 'selected' : '';
            ?>
                <option value="<?= $eid ?>" <?= $sel ?>><?= htmlspecialchars((string)($e['nombre'] ?? '')) ?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn btn-primary mb-2">Buscar</button>
    </form>

    <!-- TABLA -->
    <div class="table-responsive mb-3">
        <table class="table table-bordered table-sm">
            <thead class="thead-light">
                <tr>
                    <th class="text-center">Empresa</th>
                    <th class="text-center">No.</th>
                    <th class="text-center">Fecha</th>
                    <th class="text-center">Factura</th>

                    <th class="text-center">Proveedor</th>
                    <th>Subtotal</th>
                    <th>Impuestos</th>
                    <th>Deducciones</th>
                    <th>Total</th>
                    <th>Estado</th>
                    <th>Acciones</th>
                    <th class="text-center">Doc</th>
                    <th class="text-center">Conc.</th>
                    <th class="text-center">Siigo</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $r):
                    // 1) id y fecha

                    $id    = (int)($r['id'] ?? 0);
                    $fecha = $r['fechaSolicitud'] ? date('d-M-y g:i a', strtotime($r['fechaSolicitud'])) : '';
                    // 2) factura y proveedor+área
                    $fact  = trim((string)($r['prefijoFactura'] ?? '') . ' ' . (string)($r['noFactura'] ?? '')) ?: '-';
                    $prov  = (string)($r['Proveedor'] ?? '') . (!empty($r['Area']) ? " ({$r['Area']})" : '');
                    // 3) conciliación
                    $iconConc = '';
                    if ($r['archivo_total'] !== null) {
                        $diff = abs((float)$r['archivo_total'] - (float)$r['total']);
                        $iconConc = $diff > 10
                            ? '<i class="fas fa-times text-danger" title="Diferencia > $10"></i>'
                            : '<i class="fas fa-check text-success" title="Diferencia ≤ $10"></i>';
                    }
                    // 4) Siigo
                    $iconSiigo = $r['siigo_id'] !== null ? '<strong>S</strong>' : '';
                ?>
                    <tr>
                        <!-- 1) COLUMNA “Empresa” -->
                        <td class="text-center"
                            style="
            background-color: <?= htmlspecialchars((string)($r['EmpresaColor'] ?? '')) ?>;
            color: <?= getTextColor((string)($r['EmpresaColor'] ?? '')) ?>;
        ">
                            <strong><?= htmlspecialchars((string)($r['EmpresaSigla'] ?? '')) ?></strong>
                        </td>
                        <td class="text-center"><strong><?= $id ?></strong></td>
                        <td class="text-center"><strong><?= $fecha ?></strong></td>

                        <!-- Factura -->
                        <td class="text-center"><strong><?= htmlspecialchars($fact) ?></strong></td>



                        <!-- Proveedor -->
                        <td class="text-center"><strong><?= htmlspecialchars($prov) ?></strong></td>

                        <!-- Subtotales, impuestos, deducciones, total -->
                        <td class="text-right"><strong><?= fmt($r['subtotal']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['impuestos']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['deducciones']) ?></strong></td>
                        <td class="text-right"><strong><?= fmt($r['total']) ?></strong></td>

                        <!-- Estado -->
                        <td class="text-center"
                            style="background-color: <?= $r['EstadoColor'] ?>;
                color: <?= getTextColor($r['EstadoColor']) ?>;">
                            <strong><?= htmlspecialchars($r['Estado']) ?></strong>
                        </td>

                        <!-- Acciones -->
                        <td class="text-center">
                            <a href="pedido.php?id=<?= $id ?>" class="btn btn-sm btn-primary">Ver</a>
                        </td>
                        <!-- Doc -->
                        <td class="text-center">
                            <?php if ($r['archivo_total'] !== null): ?>
                                <a href="https://sistema.compranet.com.co/archivoDigital/<?= $r['carpeta'] ?>/<?= $r['idFactura'] ?>.pdf"
                                    target="_blank" title="Ver PDF">
                                    <i class="fas fa-file-pdf"></i>
                                </a>
                            <?php else: ?>
                                &ndash;
                            <?php endif; ?>
                        </td>

                        <!-- Conciliación -->
                        <td class="text-center"><?= $iconConc ?></td>

                        <!-- Siigo -->
                        <td class="text-center"><?= $iconSiigo ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>

        </table>
    </div>

    <!-- PAGINACIÓN -->
    <nav>
        <ul class="pagination justify-content-center">
            <?php if ($page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                        &laquo;
                    </a>
                </li>
            <?php endif; ?>
            <?php
            $start = max(1, $page - 2);
            $end   = min($totalPages, $page + 2);
            for ($p = $start; $p <= $end; $p++):
                $act = $p == $page ? ' active' : '';
            ?>
                <li class="page-item<?= $act ?>">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>">
                        <?= $p ?>
                    </a>
                </li>
            <?php endfor; ?>
            <?php if ($page < $totalPages): ?>
                <li class="page-item">
                    <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                        &raquo;
                    </a>
                </li>
            <?php endif; ?>
        </ul>
    </nav>
    </div>
    </div>

    <!-- MODAL: Crear Nuevo Pedido -->
    <!-- MODAL: Crear Nuevo Pedido -->
    <div class="modal fade" id="newOrderModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <form method="post" class="modal-content">
                <input type="hidden" name="action" value="create">
                <div class="modal-header">
                    <h5 class="modal-title">Crear Nuevo Pedido</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <!-- 1) Fecha de Solicitud -->
                    <div class="mb-3">
                        <label>Fecha de Solicitud</label>
                        <input type="date" name="fecha" class="form-control" required
                            value="<?= date('Y-m-d') ?>">
                    </div>

                    <!-- 2) NUEVO SELECT “Empresa” -->
                    <div class="mb-3">
                        <label>Empresa</label>
                        <select name="idEmpresa" class="form-control" required>
                            <option value="">Seleccione Empresa…</option>
                            <?php foreach ($empresas as $emp): ?>
                                <option value="<?= (int)($emp['id'] ?? 0) ?>">
                                    <?= htmlspecialchars((string)($emp['sigla'] ?? '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <!-- 3) Proveedor -->
                    <div class="mb-3">
                        <label>Proveedor</label>
                        <select name="idProveedorArea" class="form-control" required>
                            <?php foreach ($proveedoresAreas as $pa): ?>
                                <option value="<?= (int)($pa['id'] ?? 0) ?>"><?= htmlspecialchars((string)($pa['text'] ?? '')) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Cerrar
                    </button>
                    <button type="submit" class="btn btn-primary">Crear</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal: Pedidos por Reclamar -->
    <div class="modal fade" id="reclamarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Pedidos por Reclamar</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <?php foreach ($reclamarData as $provArea => $orders): ?>
                        <h5 class="mt-3">
                            <a data-bs-toggle="collapse" href="#collapse<?= md5($provArea) ?>"
                                aria-expanded="true" aria-controls="collapse<?= md5($provArea) ?>">
                                <?= htmlspecialchars($provArea) ?>
                            </a>
                        </h5>
                        <div class="collapse show" id="collapse<?= md5($provArea) ?>">
                            <?php foreach ($orders as $idOrden => $items): ?>
                                <h6 class="mt-2">Orden #<?= $idOrden ?> – <?= date('d-M-Y', strtotime($items[0]['fechaSolicitud'])) ?></h6>
                                <table class="table table-bordered table-sm mb-4">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Img</th>
                                            <th>CPN</th>
                                            <th>Prov</th>
                                            <th>Producto</th>
                                            <th class="text-end">Cant</th>
                                            <th class="text-end">Precio</th>
                                            <th class="text-end">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $sum = 0; ?>
                                        <?php foreach ($items as $it):
                                            $total = $it['cantidad']
                                                * $it['precioCompra']
                                                * (1 + $it['porcentajeImpuesto']);
                                            $sum += $total;
                                            $img = $it['linkImagen']
                                                ? str_replace('J:/', 'https://sistema.compranet.com.co/', $it['linkImagen'])
                                                : '';
                                        ?>
                                            <tr>
                                                <td>
                                                    <?php if ($img): ?>
                                                        <img src="<?= $img ?>" width="50" alt>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?= htmlspecialchars($it['referenciaCPN']) ?></td>
                                                <td><?= htmlspecialchars($it['referenciaProveedor']) ?></td>
                                                <td><?= htmlspecialchars($it['nombre'] . ' - ' . $it['txtColor']) ?></td>
                                                <td class="text-end"><?= intval($it['cantidad']) ?></td>
                                                <td class="text-right"><?= fmt($it['precioCompra']) ?></td>

                                                <td class="text-right"><?= fmt($total) ?></td>

                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th colspan="6" class="text-end">Total:</th>
                                            <th class="text-right"><?= fmt($sum) ?></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Cerrar
                    </button>
                </div>
            </div>
        </div>
    </div>


    <?php include '../templates/footer.php'; ?>
    </div> <!-- end content -->

    </div> <!-- end content-wrapper -->
    </div> <!-- end wrapper -->