<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/format.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/billing/BillingPurchaseOrderService.php';

require_login();
if (!user_can('module.billing') && !user_can('billing.purchase_orders') && current_user_role() !== 'admin') {
    http_response_code(403);
    die('No tienes permisos para gestionar órdenes de compra.');
}
$page_title = 'Órdenes de compra';
$service = new BillingPurchaseOrderService(db());
$filters = array('q' => trim((string)($_GET['q'] ?? '')), 'status' => trim((string)($_GET['status'] ?? '')));
$orders = $service->listOrders($filters);
$bootstrap = $service->bootstrap();
$statusLabels = array('generating' => 'Generando', 'issued' => 'Emitida', 'sent' => 'Enviada', 'cancelled' => 'Anulada');

require_once __DIR__ . '/../../layouts/header.php';
require_once __DIR__ . '/../../layouts/sidebar.php';
?>
<main class="app-main billing-integrated-main crm-ui-main" id="purchaseOrdersMain" data-spa-module="billing:purchase-orders">
    <?php require_once __DIR__ . '/../../layouts/topbar.php'; ?>
    <section class="content billing-page-shell crm-ui-page purchase-orders-page">
        <div class="page-header header-responsive crm-ui-page-header">
            <div class="page-header-content crm-ui-page-header-copy">
                <span class="label">FINANZAS · COMPRAS</span>
                <h2>Órdenes de compra</h2>
                <p class="text-muted">Documentos comerciales ICYLAB para solicitar productos y servicios a proveedores.</p>
            </div>
            <div class="cluster crm-ui-page-actions">
                <a class="btn btn-outline" href="/modules/billing/"><i data-lucide="file-plus-2"></i><span>Emitir DTE</span></a>
                <button class="btn btn-primary" type="button" id="poNewBtn"><i data-lucide="plus"></i><span>Nueva orden</span></button>
            </div>
        </div>

        <div class="manual-alert manual-alert-info po-information"><strong>Documento no tributario.</strong> La OC se numera y genera en ICYLAB; no se envía a FACTO ni al SII.</div>

        <section class="card po-filter-card">
            <form class="po-filter-form" method="get" action="/modules/billing/purchase_orders.php" data-spa-form="true">
                <input class="input" name="q" value="<?php echo safe_text($filters['q']); ?>" placeholder="Buscar por número, proveedor o RUT">
                <select class="input" name="status">
                    <option value="">Todos los estados</option>
                    <?php foreach ($statusLabels as $value => $label): ?>
                        <?php if ($value === 'generating') continue; ?>
                        <option value="<?php echo safe_text($value); ?>" <?php echo $filters['status'] === $value ? 'selected' : ''; ?>><?php echo safe_text($label); ?></option>
                    <?php endforeach; ?>
                </select>
                <button class="btn btn-primary" type="submit"><i data-lucide="search"></i><span>Buscar</span></button>
                <?php if ($filters['q'] !== '' || $filters['status'] !== ''): ?><a class="btn btn-outline" href="/modules/billing/purchase_orders.php"><i data-lucide="x"></i><span>Limpiar</span></a><?php endif; ?>
            </form>
        </section>

        <section class="card crm-ui-table-card po-table-card">
            <div class="card-header crm-ui-table-toolbar"><div><h3>Órdenes emitidas</h3><p><?php echo count($orders); ?> resultado(s)</p></div></div>
            <div class="crm-ui-table-scroll po-table-scroll">
                <table class="crm-ui-table po-table">
                    <thead><tr><th>Orden</th><th>Proveedor</th><th>Emisión</th><th>Entrega</th><th>Total</th><th>Estado</th><th></th></tr></thead>
                    <tbody>
                    <?php if (!$orders): ?>
                        <tr><td colspan="7"><div class="po-empty"><i data-lucide="clipboard-list"></i><strong>No hay órdenes de compra</strong><span>Crea la primera orden para comenzar.</span></div></td></tr>
                    <?php endif; ?>
                    <?php foreach ($orders as $order): ?>
                        <?php $status = (string)$order['status']; ?>
                        <tr>
                            <td><strong><?php echo safe_text($order['order_number']); ?></strong><small><?php echo safe_text($order['requested_by_name'] ?: 'ICYLAB'); ?></small></td>
                            <td><strong><?php echo safe_text($order['supplier_legal_name']); ?></strong><small><?php echo safe_text($order['supplier_tax_id'] ?: 'Sin RUT'); ?></small></td>
                            <td><?php echo safe_text(date('d-m-Y', strtotime($order['issue_date']))); ?></td>
                            <td><?php echo $order['expected_delivery_date'] ? safe_text(date('d-m-Y', strtotime($order['expected_delivery_date']))) : 'Por coordinar'; ?></td>
                            <td><strong><?php echo safe_text($order['currency_code']); ?> <?php echo number_format((float)$order['total_amount'], $order['currency_code'] === 'CLP' ? 0 : 2, ',', '.'); ?></strong></td>
                            <td><span class="badge <?php echo $status === 'sent' ? 'badge-success' : ($status === 'cancelled' ? 'badge-error' : ''); ?>"><?php echo safe_text($statusLabels[$status] ?? ucfirst($status)); ?></span></td>
                            <td><div class="po-row-actions">
                                <a class="btn btn-outline action-square-btn" href="/modules/billing/purchase_order_file.php?id=<?php echo (int)$order['id']; ?>" target="_blank" rel="noopener" title="Ver PDF"><i data-lucide="file-text"></i></a>
                                <?php if ($status !== 'cancelled'): ?><button class="btn btn-outline action-square-btn po-send-btn" type="button" data-order-id="<?php echo (int)$order['id']; ?>" data-order-number="<?php echo safe_text($order['order_number']); ?>" data-email="<?php echo safe_text($order['supplier_email']); ?>" title="Enviar al proveedor"><i data-lucide="mail"></i></button><?php endif; ?>
                            </div></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </section>

    <div class="product-modal-backdrop crm-ui-modal-backdrop po-modal-backdrop" id="poCreateModal" aria-hidden="true" role="dialog" aria-modal="true">
        <div class="product-modal-box crm-ui-modal-box po-modal-box" role="document">
            <header class="product-modal-header crm-ui-modal-header">
                <button class="btn btn-outline action-square-btn" id="poBackBtn" type="button" aria-label="Volver"><i data-lucide="arrow-left"></i></button>
                <div><h2 id="poModalTitle">Nueva orden de compra</h2><p id="poModalSubtitle">Documento comercial ICYLAB</p></div>
                <button class="btn btn-outline action-square-btn" id="poCloseBtn" type="button" aria-label="Cerrar"><i data-lucide="x"></i></button>
            </header>
            <div class="product-modal-body crm-ui-modal-body po-modal-body">
                <nav class="manual-stepbar po-stepbar" id="poStepbar">
                    <span data-step="supplier">1. Proveedor</span><span data-step="items">2. Productos</span><span data-step="conditions">3. Entrega</span><span data-step="review">4. Revisar</span>
                </nav>
                <div id="poError" class="manual-alert manual-alert-error" style="display:none"></div>
                <div id="poLayerContent"></div>
            </div>
            <footer class="product-modal-footer crm-ui-modal-footer" id="poModalFooter"></footer>
        </div>
    </div>

    <div class="product-modal-backdrop crm-ui-modal-backdrop po-email-backdrop" id="poEmailModal" aria-hidden="true" role="dialog" aria-modal="true">
        <div class="product-modal-box crm-ui-modal-box po-email-box" role="document">
            <header class="product-modal-header crm-ui-modal-header"><div><h2>Enviar orden de compra</h2><p>El PDF se adjuntará automáticamente.</p></div><button class="btn btn-outline action-square-btn" id="poEmailClose" type="button"><i data-lucide="x"></i></button></header>
            <div class="product-modal-body crm-ui-modal-body">
                <div id="poEmailError" class="manual-alert manual-alert-error" style="display:none"></div>
                <div class="po-email-form">
                    <label><span>Destinatario</span><input class="input" type="email" id="poEmailTo"></label>
                    <label><span>Asunto</span><input class="input" id="poEmailSubject"></label>
                    <label><span>Mensaje</span><textarea class="input" id="poEmailBody" rows="7"></textarea></label>
                </div>
            </div>
            <footer class="product-modal-footer crm-ui-modal-footer"><button class="btn btn-outline" type="button" id="poEmailCancel">Cancelar</button><button class="btn btn-primary" type="button" id="poEmailSend"><i data-lucide="send"></i><span>Enviar con PDF</span></button></footer>
        </div>
    </div>

    <script>
    window.ICY_PURCHASE_ORDER_BOOTSTRAP = <?php echo json_encode($bootstrap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    window.ICY_PURCHASE_ORDER_OPEN_NEW = <?php echo !empty($_GET['new']) ? 'true' : 'false'; ?>;
    </script>
    <?php $poJsVersion = @filemtime(__DIR__ . '/purchase_orders.js') ?: time(); ?>
    <script src="/modules/billing/purchase_orders.js?v=<?php echo (int)$poJsVersion; ?>"></script>
</main>
<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
