<?php
// 1. INICIO DE SESIÓN Y CONEXIÓN
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

include 'includes/db.php';
include 'includes/header.php';

// 2. LÓGICA DE EDICIÓN (Igual a suspension.php)
$edit_mode = false;
$orden_data = [];
$items_realizados = [];

if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $pdo->prepare("SELECT o.*, c.nombres_apellido FROM ordenes_frenos 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;
        $detalles = json_decode($orden_data['detalles_items'], true);
        if (is_array($detalles)) {
            foreach ($detalles as $d) {
                $items_realizados[$d['descripcion']] = [
                    'realizado' => $d['realizado'] == 'SI',
                    'precio' => $d['precio']
                ];
            }
        }
    }
}

// 3. LISTADO DE ÍTEMS DE FRENOS (Divididos para las 2 columnas)
$items_izq = [
    "Pastillas de freno delanteras",
    "Pastillas de Freno Traseras",
    "Cintas de freno",
    "Flexibles de freno",
    "Caño de frenos",
    "Cilindros de freno",
    "Liquido de frenos Tipo",
    "Campanas",
    "Discos"
];

$items_der = [
    "Rectificar campanas",
    "Juego reparacion",
    "Encintar",
    "Reten/es",
    "Rectificar discos",
    "Juego clavos de freno",
    "Juego zapatas nuevas",
    "Mano de obra"
];
?>

<div class="p-4" style="position: relative; z-index: 10;">
    <div class="container-bg bg-white p-4 shadow-sm rounded">

        <div class="row mb-4 align-items-center">
            <div class="col-md-4">
                <a href="frenos.php" class="text-decoration-underline text-dark fw-bold">Nueva Orden</a>
            </div>
            <div class="col-md-4 text-center">
                <h4 class="fw-bold m-0">Orden de Trabajo FRENOS</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>

        <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="frenos">
            <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="<?= $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%">CLIENTE</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>
                        <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>
                </tbody>
            </table>

            <div class="row">
                <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 foreach ($items_izq as $i => $item):
                                $checked = (isset($items_realizados[$item]) && $items_realizados[$item]['realizado']) ? 'checked' : '';
                                $precio_val = $items_realizados[$item]['precio'] ?? '';
                                ?>
                                <tr>
                                    <td class="ps-2"><?= $item ?><input type="hidden" name="item_nombre[]"
                                            value="<?= $item ?>"></td>
                                    <td class="text-center p-0 align-middle">
                                        <input type="checkbox" name="item_check[<?= $i ?>]" <?= $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 endforeach; ?>
                        </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>

                <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
                            $offset = count($items_izq);
                            foreach ($items_der as $j => $item):
                                $idx = $offset + $j;
                                $checked = (isset($items_realizados[$item]) && $items_realizados[$item]['realizado']) ? 'checked' : '';
                                $precio_val = $items_realizados[$item]['precio'] ?? '';
                                ?>
                                <tr>
                                    <td class="ps-2"><?= $item ?><input type="hidden" name="item_nombre[]"
                                            value="<?= $item ?>"></td>
                                    <td class="text-center p-0 align-middle">
                                        <input type="checkbox" name="item_check[<?= $idx ?>]" <?= $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 endforeach; ?>
                        </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>

            <div class="row justify-content-end mt-3">
                <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 no-print">
                <a href="index.php" class="btn btn-outline-secondary me-3">Cancelar</a>
                <button type="submit" class="btn btn-primary px-5 fw-bold">
                    <?= $edit_mode ? 'Guardar Cambios' : 'Guardar Orden' ?>
                </button>
            </div>
        </form>
    </div>
</div>

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