<?php
include 'includes/header.php';

// EDICIÓN: Verificar si viene edit_id
$edit_mode = false;
$orden_data = [];
$items_realizados = []; // format: index => ['nombre'=>'...', 'precio'=>...]

if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $pdo->prepare("SELECT o.*, c.nombres_apellido FROM ordenes_otros o LEFT JOIN clientes c ON o.cliente_id = c.id WHERE o.id = ?");
    $stmt->execute([$edit_id]);
    $orden_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($orden_data) {
        $edit_mode = true;
        // Parsear trabajos_realizados (formato texto: "Nombre ($Precio)\n")
        $patron = '/^(.*)\s\(\$([0-9\.]+)\)$/';
        $lineas = explode("\n", $orden_data['trabajos_realizados']);
        foreach ($lineas as $linea) {
            $linea = trim($linea);
            if (!empty($linea)) {
                if (preg_match($patron, $linea, $matches)) {
                    $items_realizados[] = ['nombre' => $matches[1], 'precio' => $matches[2]];
                } else {
                    // Fallback si no matchea precio
                    $items_realizados[] = ['nombre' => $linea, 'precio' => 0];
                }
            }
        }
    }
}
?>

<div class="p-4" style="position: relative; z-index: 10;">
        <div class="container-bg bg-white p-4 shadow-sm rounded">
            <!-- Header de Orden -->
            <div class="row mb-4 align-items-center">
                <div class="col-md-4">
                    <a href="otros.php" class="text-decoration-underline text-dark fw-bold">Crear Nueva Orden</a>
                </div>
                <div class="col-md-4 text-center">
                    <h4 class="fw-bold">Orden de Trabajo OTROS</h4>
                </div>
                <div class="col-md-4 d-flex justify-content-end align-items-center">
                    <label class="me-2 fw-bold">Orden N.</label>
                    <input type="text" form="form-orden" name="orden_num" value="<?= $edit_mode ? $orden_data['orden_num'] : '' ?>"
                        class="form-control d-inline-block border-dark" style="width: 150px; border-width: 2px;">
                </div>
            </div>

            <!-- Datos del Cliente / Vehiculo -->
            <form id="form-orden" method="POST" action="procesar_orden.php">
                <input type="hidden" name="guardar_orden" value="1">
                <input type="hidden" name="tipo_orden" value="otros">
                <input type="hidden" name="cliente_id" id="cliente_id" value="<?= $edit_mode ? $orden_data['cliente_id'] : '' ?>">
                <?php if($edit_mode): ?>
                
                <input type="hidden" name="orden_id" value="<?= $edit_mode ? $orden_data['id'] : '' ?>">
                <input type="hidden" name="tipo_orden" value="otros"> ```
                
<!-- <input type="hidden" name="orden_id" value="<?//= $orden_data['id'] ?>"> -->
                
                <?php endif; ?>

                <table class="table table-bordered border-dark border-2 mb-4">
                    <thead class="text-center fw-bold">
                        <tr>
                            <th width="25%">NOMBRES Y APELLIDO</th>
                            <th width="15%">FECHA</th>
                            <th width="30%">VEHICULO Marca/Modelo</th>
                            <th width="15%">PATENTE</th>
                            <th width="15%">KMS</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                        <tr>
                            <td class="p-0"><input type="text" name="cliente" id="cliente" required value="<?= $edit_mode ? ($orden_data['nombres_apellido'] ?? '') : '' ?>"
                                    class="form-control border-0 rounded-0 shadow-none text-center"></td>
                            <td class="p-0"><input type="date" name="fecha" value="<?= $edit_mode ? $orden_data['fecha'] : date('Y-m-d') ?>"
                                    class="form-control border-0 rounded-0 shadow-none text-center"></td>
                            <td class="p-0"><input type="text" name="vehiculo" id="vehiculo" required value="<?= $edit_mode ? $orden_data['vehiculo'] : '' ?>"
                                    class="form-control border-0 rounded-0 shadow-none text-center"></td>
                            <td class="p-0"><input type="text" name="patente" id="patente" required value="<?= $edit_mode ? $orden_data['patente'] : '' ?>"
                                    class="form-control border-0 rounded-0 shadow-none text-center"></td>
                            <td class="p-0"><input type="text" name="kms" id="kms" value="<?= $edit_mode ? $orden_data['kms'] : '' ?>"
                                    class="form-control border-0 rounded-0 shadow-none text-center"></td>
                        </tr>
                        </tr>
                    </tbody>
                </table>

                <!-- Items Doble Columna - Todos editables para OTROS -->
                <div class="row">
                    <!-- Columna Izquierda -->
                    <div class="col-md-6">
                        <table class="table table-bordered border-dark border-2 table-sm align-middle">
                            <thead class="text-center bg-light">
                                <tr>
                                    <th width="60%">ITEMS</th>
                                    <th width="20%">SI / NO</th>
                                    <th width="20%">$</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php for ($i = 0; $i < 8; $i++): 
                                    $item_actual = $items_realizados[$i] ?? null;
                                    $nombre_val = $item_actual ? $item_actual['nombre'] : '';
                                    $precio_val = $item_actual ? $item_actual['precio'] : '';
                                    ?>
                                    <tr>
                                        <td class="p-0">
                                            <input type="text" name="item_nombre[]" value="<?= $nombre_val ?>"
                                                class="form-control border-0 shadow-none ps-2" placeholder="">
                                        </td>
                                        <td class="text-center p-0 align-middle">
                                            <input type="checkbox" name="item_check[<?= $i ?>]" <?= $item_actual ? 'checked' : '' ?>
                                                class="form-check-input mt-0">
                                        </td>
                                        <td class="p-0">
                                            <input type="number" name="item_precio[<?= $i ?>]" value="<?= $precio_val ?>"
                                                class="form-control form-control-sm border-0 shadow-none text-end price-input"
                                                step="0.01">
                                        </td>
                                    </tr>
                                <?php endfor; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="2" class="text-end fw-bold pe-2 border-top border-dark">SunTotal 1</td>
                                    <td class="p-0 border-top border-dark">
                                        <input type="text" id="subtotal1"
                                            class="form-control form-control-sm border-0 fw-bold text-end bg-white"
                                            readonly value="0.00">
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Columna Derecha -->
                    <div class="col-md-6">
                        <table class="table table-bordered border-dark border-2 table-sm align-middle">
                            <thead class="text-center bg-light">
                                <tr>
                                    <th width="60%">ITEMS</th>
                                    <th width="20%">SI / NO</th>
                                    <th width="20%">$</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php for ($j = 0; $j < 8; $j++):
                                    $idx = 8 + $j;
                                    $item_actual = $items_realizados[$idx] ?? null;
                                    $nombre_val = $item_actual ? $item_actual['nombre'] : '';
                                    $precio_val = $item_actual ? $item_actual['precio'] : '';
                                    ?>
                                    <tr>
                                        <td class="p-0">
                                            <input type="text" name="item_nombre[]" value="<?= $nombre_val ?>"
                                                class="form-control border-0 shadow-none ps-2" placeholder="">
                                        </td>
                                        <td class="text-center p-0 align-middle">
                                            <input type="checkbox" name="item_check[<?= $idx ?>]" <?= $item_actual ? 'checked' : '' ?>
                                                class="form-check-input mt-0">
                                        </td>
                                        <td class="p-0">
                                            <input type="number" name="item_precio[<?= $idx ?>]" value="<?= $precio_val ?>"
                                                class="form-control form-control-sm border-0 shadow-none text-end price-input-2"
                                                step="0.01">
                                        </td>
                                    </tr>
                                <?php endfor; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="2" class="text-end fw-bold pe-2 border-top border-dark">SunTotal 2</td>
                                    <td class="p-0 border-top border-dark">
                                        <input type="text" id="subtotal2"
                                            class="form-control form-control-sm border-0 fw-bold text-end bg-white"
                                            readonly value="0.00">
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

                <!-- Footer Total -->
                <div class="row justify-content-end mt-2">
                    <div class="col-md-3">
                        <div class="input-group border border-2 border-dark">
                            <span class="input-group-text bg-white border-0 fw-bold">TOTAL</span>
                            <input type="text" id="total_general" name="total_final" value="<?= $edit_mode ? $orden_data['total'] : '0.00' ?>"
                                class="form-control form-control-lg border-0 fw-bold text-center bg-white" readonly>
                        </div>
                    </div>
                </div>

                <div class="mt-4 shadow-sm p-3 bg-light rounded d-flex justify-content-end">
                    <a href="index.php" class="btn btn-outline-secondary me-2">Cancelar</a>
                    <button type="submit" class="btn btn-primary px-5">Guardar Cambios</button>
                </div>

            </form>
        </div>
</div>



<?php include 'includes/footer.php'; ?>
<script src="assets/js/autocompletado_ordenes.js"></script>