<?php
session_start();
$host = 'localhost';
$db = 'trabajadores';
$username = 'root';
$password = 'root';

if (!isset($_SESSION['usuario'])) {
    header("Location: index.html");
    exit;
}

try {
    $conn = new mysqli($host, $username, $password, $db);

    if ($conn->connect_error) {
        die("Conexión fallida: " . $conn->connect_error);
    }

    $usuario = $_SESSION['usuario'];

    $sql = "SELECT NOMBRE, ROL FROM personal WHERE USUARIO = '$usuario'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $nombre = $row['NOMBRE'];
        $rol = $row['ROL'];

        // 👉 Agregamos la función para sacar iniciales
        function obtenerIniciales($nombreCompleto)
        {
            $partes = explode(' ', $nombreCompleto);
            $iniciales = '';

            foreach ($partes as $parte) {
                if (!empty($parte)) {
                    $iniciales .= strtoupper($parte[0]);
                }
            }
            return $iniciales;
        }

        // 👉 Ahora creamos las iniciales
        $inicialesUsuario = obtenerIniciales($nombre);
    } else {
        $nombre = "Usuario";
        $rol = "Usuario";
        $inicialesUsuario = "US"; // Algo por defecto
    }

    $conn->close();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en" class="light-style layout-menu-fixed" dir="ltr" data-theme="theme-default" data-assets-path="../assets/" data-template="vertical-menu-template-free">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <title>Ordenes de Servicio</title>
    <meta name="description" content="" />
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="../assets/img/favicon/favicon.ico" />
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet" />


    <!-- Icons. Uncomment required icon fonts -->
    <link rel="stylesheet" href="../assets/vendor/fonts/boxicons.css" />

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">





    <!-- Core CSS -->
    <link rel="stylesheet" href="../assets/vendor/css/core.css" class="template-customizer-core-css" />
    <link rel="stylesheet" href="../assets/vendor/css/theme-default.css" class="template-customizer-theme-css" />
    <link rel="stylesheet" href="../assets/css/demo.css" />

    <!-- Vendors CSS -->
    <link rel="stylesheet" href="../assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css" />

    <link rel="stylesheet" href="../assets/vendor/libs/apex-charts/apex-charts.css" />

    <!-- Page CSS -->

    <!-- Helpers -->
    <script src="../assets/vendor/js/helpers.js"></script>
    <script src="../assets/js/config.js"></script>

    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <style>
        .wow {
            visibility: hidden;
        }
    </style>
</head>

<body>
    <!-- Layout wrapper -->
    <div class="layout-wrapper layout-content-navbar">
        <div class="layout-container">
            <!-- Menu -->

            <aside id="layout-menu" class="layout-menu menu-vertical menu bg-menu-theme">
                <div class="app-brand demo">
                    <a href="index.html" class="app-brand-link">
                        <span class="app-brand-logo demo">
                            <svg
                                version="1.1"
                                xmlns="http://www.w3.org/2000/svg"
                                xmlns:xlink="http://www.w3.org/1999/xlink"
                                x="0px"
                                y="0px"
                                viewBox="0 0 2000 2000"
                                style="enable-background:new 0 0 2000 2000;"
                                xml:space="preserve"
                                width="100"
                                height="100">
                                <style type="text/css">
                                    .st0 {
                                        display: none;
                                    }

                                    .st1 {
                                        fill: #009DFF;
                                    }
                                </style>
                                <g id="Capa_1" class="st0">
                                    <image style="display:inline;overflow:visible;" width="2550" height="1558" transform="matrix(1 0 0 1 494.3726 289.1373)"></image>
                                </g>
                                <g id="Capa_2">
                                    <g>
                                        <rect x="183.89" y="18.31" class="st1" width="1632.23" height="526.02" />
                                        <polygon class="st1" points="1031.3,1629.99 1031.3,1711.86 1308.44,1711.86 1308.44,1825.3 1031.3,1825.3 1031.3,1907.13 1308.44,1907.13 1308.44,1981.69 691.56,1981.69 691.56,682.4 1308.44,682.4 1308.44,1629.99" />
                                    </g>
                                </g>
                                <g id="Capa_3" class="st0"></g>
                            </svg>
                        </span>
                        <span class="app-brand-text demo menu-text fw-bolder ms-2">Trax</span>
                    </a>

                    <a href="javascript:void(0);" class="layout-menu-toggle menu-link text-large ms-auto d-block d-xl-none">
                        <i class="bx bx-chevron-left bx-sm align-middle"></i>
                    </a>
                </div>

                <div class="menu-inner-shadow"></div>

                <ul class="menu-inner py-1">
                    <!-- Dashboard
                     <li class="menu-item active">
                       <a href="index.html" class="menu-link">
                         <i class="menu-icon tf-icons bx bx-home-circle"></i>
                         <div data-i18n="Analytics">Dashboard</div>
                       </a>
                     </li> -->


                    <!-- Layouts -->
                    <li class="menu-item ">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-layout"></i>
                            <div data-i18n="Layouts">Inicio</div>
                        </a>

                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="tablero.php" class="menu-link">
                                    <div data-i18n="Without menu">Tablero</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nuevo_cliente.php" class="menu-link">
                                    <div data-i18n="Without navbar">Agregar Cliente</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nuevo_proveedor.php" class="menu-link">
                                    <div data-i18n="Container">Agregar Proveedor</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nueva_cotizacion.php" class="menu-link">
                                    <div data-i18n="Fluid">Agregar Cotizacion</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="nuevo_producto.php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Producto</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="nueva_compra.php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Compra</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="nueva_factura.php" class="menu-link">
                                    <div data-i18n="Blank">Agregar Factura</div>
                                </a>
                            </li>

                        </ul>
                    </li>

                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Aspel SAE</span>
                    </li>
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-line-chart"></i>
                            <div data-i18n="Account Settings">Ventas</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="facturas.php" class="menu-link">
                                    <div data-i18n="Account">Facturas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="notasdeventa.php" class="menu-link">
                                    <div data-i18n="Notifications">Notas de Venta</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="trasladoscartaporte.php" class="menu-link">
                                    <div data-i18n="Connections">Carta Porte</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="remisiones.php" class="menu-link">
                                    <div data-i18n="Connections">Remisiones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="pedidos.php" class="menu-link">
                                    <div data-i18n="Connections">Pedidos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cotizaciones.php" class="menu-link">
                                    <div data-i18n="Connections">Cotizaciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="devoluciones.php" class="menu-link">
                                    <div data-i18n="Connections">Devoluciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="notasdecredito.php" class="menu-link">
                                    <div data-i18n="Connections">Notas de Crédito</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="parcialidades.php" class="menu-link">
                                    <div data-i18n="Connections">Parcialidades</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="comprobantesdepago.php" class="menu-link">
                                    <div data-i18n="Connections">Comprobantes</div>
                                </a>
                            <li class="menu-item">
                                <a href="estadisticas.php" class="menu-link">
                                    <div data-i18n="Connections">Estadisticas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticascli.php" class="menu-link">
                                    <div data-i18n="Connections">Ventas X Cliente</div>
                                </a>
                            </li>
                        </ul>
                    </li>

                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-user"></i>
                            <div data-i18n="Authentications">Clientes</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="clientes.php" class="menu-link">
                                    <div data-i18n="Basic">Clientes</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="correos.php" class="menu-link">
                                    <div data-i18n="Basic">Correos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cuentasxcobrar.php" class="menu-link">
                                    <div data-i18n="Basic">Cuentas X Cobrar</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="clientespoliza.php" class="menu-link">
                                    <div data-i18n="Basic">Clientes con Póliza</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="clientestimbres.php" class="menu-link">
                                    <div data-i18n="ClientStamps">Clientes Timbres</div>
                                </a>
                            </li>

                            <li class="menu-item">
                                <a href="clientesistemas.php" class="menu-link">
                                    <div data-i18n="ClientSystems">Clientes Sistemas</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-package"></i>
                            <div data-i18n="Misc">Inventarios</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="productos.php" class="menu-link">
                                    <div data-i18n="Error">Productos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="existencias.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Existencias</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-shopping-bag"></i>
                            <div data-i18n="Misc">Compras</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="compras.php" class="menu-link">
                                    <div data-i18n="Error">Compras</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="recepciones.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Recepciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="ordenes.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Ordenes</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="requisiciones.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Requisiciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="devolucionescom.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Devoluciones</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticasprove.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Compras X Proveedor</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-group"></i>
                            <div data-i18n="Misc">Proveedores</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="proveedores.php" class="menu-link">
                                    <div data-i18n="Error">Proveedores</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="cuentasxpagar.php" class="menu-link">
                                    <div data-i18n="Under Maintenance">Cuentas X Pagar</div>
                                </a>
                            </li>
                        </ul>
                    </li>


                    <!-- Aspel COI -->
                    <li class="menu-header small text-uppercase"><span class="menu-header-text">Aspel COI</span></li>

                    <!-- Extended components -->
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-copy"></i>
                            <div data-i18n="Extended UI">Cuentas y Pólizas</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item">
                                <a href="cuentas.php" class="menu-link">
                                    <div data-i18n="Perfect Scrollbar">Cuentas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="polizas.php" class="menu-link">
                                    <div data-i18n="Text Divider">Pólizas</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="activos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Activos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="auxiliares.php" class="menu-link">
                                    <div data-i18n="Text Divider">Auxiliares</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="presupuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Presupuestos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="presupuestosPD.php" class="menu-link">
                                    <div data-i18n="Text Divider">Presupuestos DP</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="monedas.php" class="menu-link">
                                    <div data-i18n="Text Divider">Monedas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="departamentos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Departamentos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="otrosimpuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Otros Impuestos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="activosgenerales.php" class="menu-link">
                                    <div data-i18n="Text Divider">Activos Generales</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="saldos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Saldos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="saldosDP.php" class="menu-link">
                                    <div data-i18n="Text Divider">Saldos DP</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="rubros.php" class="menu-link">
                                    <div data-i18n="Text Divider">Rubros</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="ccostos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Centro de Costos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="concepto.php" class="menu-link">
                                    <div data-i18n="Text Divider">Conceptos</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="regpol.php" class="menu-link">
                                    <div data-i18n="Text Divider">Registro de Pólizas</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="impuestos.php" class="menu-link">
                                    <div data-i18n="Text Divider">Impuestos</div>
                                </a>
                            </li>
                            <li class="menu-item ">
                                <a href="timbres.php" class="menu-link">
                                    <div data-i18n="Text Divider">Timbres</div>
                                </a>
                            </li>
                        </ul>
                    </li>

                    <!-- Aspel BANCO -->
                    <li class="menu-header small text-uppercase"><span class="menu-header-text">Aspel BANCO</span></li>
                    <!-- Forms -->
                    <li class="menu-item">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-credit-card"></i>
                            <div data-i18n="Form Elements">Movimientos</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item ">
                                <a href="movimientos.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="moneda.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Moneda</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="beneficiosxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Beneficios</div>
                                </a>

                            </li>
                            <li class="menu-item ">
                                <a href="cuentasxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Cuentas ban</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="formadepagoxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Forma de pago</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="parametrosxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Partidas de movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="comprobantedeldocumentoxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Comprobante del documento</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="centrodecuentasxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Conceptos de movimientos</div>
                                </a>

                            </li>
                            <li class="menu-item">
                                <a href="historialxban.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Historial</div>
                                </a>

                            </li>
                        </ul>
                    </li>
                    <li class="menu-header small text-uppercase">
                        <span class="menu-header-text">Mantenimiento y Soporte</span>
                    </li>
                    <li class="menu-item active open">
                        <a href="#" class="menu-link menu-toggle">
                            <i class="menu-icon tf-icons bx bx-credit-card"></i>
                            <div data-i18n="Form Elements">Mantenimiento</div>
                        </a>
                        <ul class="menu-sub">
                            <li class="menu-item active">
                                <a href="ordenservicio.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Ordenes de Servicio</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="registrossemana.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Registros</div>
                                </a>
                            </li>
                            <li class="menu-item">
                                <a href="estadisticasord.php" class="menu-link">
                                    <div data-i18n="Basic Inputs">Estadisticas</div>
                                </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </aside>
            <!-- / Menu -->


            <!-- Layout container -->
            <div class="layout-page">
                <!-- Navbar -->

                <nav class="layout-navbar container-xxl navbar navbar-expand-xl navbar-detached align-items-center bg-navbar-theme" id="layout-navbar">
                    <div class="layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none">
                        <a class="nav-item nav-link px-0 me-xl-4" href="javascript:void(0)">
                            <i class="bx bx-menu bx-sm"></i>
                        </a>
                    </div>

                    <div class="navbar-nav-right d-flex align-items-center" id="navbar-collapse">
                        <!-- Search -->
                        <div class="navbar-nav align-items-center">
                            <div class="nav-item d-flex align-items-center">
                                <i class="bx bx-search fs-4 lh-0"></i>
                                <input
                                    type="text"
                                    class="form-control border-0 shadow-none"
                                    placeholder="Buscar..."
                                    aria-label="Buscar..." />
                            </div>
                        </div>
                        <!-- /Search -->

                        <ul class="navbar-nav flex-row align-items-center ms-auto">


                            <!-- icono de idioma  -->
                            <li class="nav-item dropdown-language dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="icon-base bx bx-globe icon-md"></i>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-end" data-bs-popper="static">
                                    <li>
                                        <a class="dropdown-item active" href="javascript:void(0);" data-language="en" data-text-direction="ltr">
                                            <span>English</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="fr" data-text-direction="ltr">
                                            <span>French</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="ar" data-text-direction="rtl">
                                            <span>Arabic</span>
                                        </a>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="javascript:void(0);" data-language="de" data-text-direction="ltr">
                                            <span>German</span>
                                        </a>
                                    </li>
                                </ul>
                            </li>


                            <!-- Icono de modo oscuro -->
                            <li class="nav-item dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" id="nav-theme" href="javascript:void(0);" data-bs-toggle="dropdown" aria-label="Toggle theme (light)">
                                    <i class="bx-sun icon-base bx icon-md theme-icon-active"></i>
                                    <span class="d-none ms-2" id="nav-theme-text">Toggle theme</span>
                                </a>


                                <!-- Submenu de modo oscuro -->
                                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="nav-theme-text" data-bs-popper="static">
                                    <li>
                                        <button type="button" class="dropdown-item align-items-center active" data-bs-theme-value="light" aria-pressed="true">
                                            <span>
                                                <i class="icon-base bx bx-sun icon-md me-3" data-icon="sun"></i>Light
                                            </span>
                                        </button>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item align-items-center" data-bs-theme-value="dark" aria-pressed="false">
                                            <span>
                                                <i class="icon-base bx bx-moon icon-md me-3" data-icon="moon"></i>Dark
                                            </span>
                                        </button>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item align-items-center" data-bs-theme-value="system" aria-pressed="false">
                                            <span>
                                                <i class="icon-base bx bx-desktop icon-md me-3" data-icon="desktop"></i>System
                                            </span>
                                        </button>
                                    </li>

                                </ul>
                                <!-- Aquí termina submenu -->
                            </li>


                            <li class="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                                    <i class="icon-base bx bx-grid-alt icon-md"></i>
                                </a>
                                <!-- submenu -->
                                <div class="dropdown-menu dropdown-menu-end p-0">
                                    <div class="dropdown-menu-header border-bottom">
                                        <div class="dropdown-header d-flex align-items-center py-3">
                                            <h6 class="mb-0 me-auto">Shortcuts</h6>
                                            <a href="javascript:void(0)" class="dropdown-shortcuts-add py-2" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Add shortcuts" data-bs-original-title="Add shortcuts"><i class="icon-base bx bx-plus-circle text-heading"></i></a>
                                        </div>
                                    </div>
                                    <div class="dropdown-shortcuts-list scrollable-container ps">
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-calendar icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-calendar.html" class="stretched-link">Calendar</a>
                                                <small>Appointments</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-food-menu icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-invoice-list.html" class="stretched-link">Invoice App</a>
                                                <small>Manage Accounts</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-user icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-user-list.html" class="stretched-link">User App</a>
                                                <small>Manage Users</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-check-shield icon-26px text-heading"></i>
                                                </span>
                                                <a href="app-access-roles.html" class="stretched-link">Role Management</a>
                                                <small>Permission</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-pie-chart-alt-2 icon-26px text-heading"></i>
                                                </span>
                                                <a href="index.html" class="stretched-link">Dashboard</a>
                                                <small>User Dashboard</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-cog icon-26px text-heading"></i>
                                                </span>
                                                <a href="pages-account-settings-account.html" class="stretched-link">Setting</a>
                                                <small>Account Settings</small>
                                            </div>
                                        </div>
                                        <div class="row row-bordered overflow-visible g-0">
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-help-circle icon-26px text-heading"></i>
                                                </span>
                                                <a href="pages-faq.html" class="stretched-link">FAQs</a>
                                                <small>FAQs &amp; Articles</small>
                                            </div>
                                            <div class="dropdown-shortcuts-item col">
                                                <span class="dropdown-shortcuts-icon rounded-circle mb-3">
                                                    <i class="icon-base bx bx-window-open icon-26px text-heading"></i>
                                                </span>
                                                <a href="modal-examples.html" class="stretched-link">Modals</a>
                                                <small>Useful Popups</small>
                                            </div>
                                        </div>
                                        <div class="ps__rail-x" style="left: 0px; bottom: 0px;">
                                            <div class="ps__thumb-x" tabindex="0" style="left: 0px; width: 0px;"></div>
                                        </div>
                                        <div class="ps__rail-y" style="top: 0px; right: 0px;">
                                            <div class="ps__thumb-y" tabindex="0" style="top: 0px; height: 0px;"></div>
                                        </div>
                                    </div>
                                </div>
                                <!-- aqui termina submenu -->

                            </li>

                            <li class="nav-item dropdown-notifications navbar-dropdown dropdown me-3 me-xl-2">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
                                    <span class="position-relative">
                                        <i class="icon-base bx bx-bell icon-md"></i>
                                        <span class="badge rounded-pill bg-danger badge-dot badge-notifications border"></span>
                                    </span>
                                </a>

                                <!--empiezan las notificaciones -->
                                <ul class="dropdown-menu dropdown-menu-end p-0">
                                    <li class="dropdown-menu-header border-bottom">
                                        <div class="dropdown-header d-flex align-items-center py-3">
                                            <h6 class="mb-0 me-auto">Notification</h6>
                                            <div class="d-flex align-items-center h6 mb-0">
                                                <span class="badge bg-label-primary me-2">8 New</span>
                                                <a href="javascript:void(0)" class="dropdown-notifications-all p-2" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Mark all as read" data-bs-original-title="Mark all as read"><i class="icon-base bx bx-envelope-open text-heading"></i></a>
                                            </div>
                                        </div>
                                    </li>


                                    <li class="dropdown-notifications-list scrollable-container ps">
                                        <ul class="list-group list-group-flush">
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <img src="../../assets/img/avatars/1.png" alt="" class="rounded-circle">
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">Congratulation Lettie 🎉</h6>
                                                        <small class="mb-1 d-block text-body">Won the monthly best seller gold badge</small>
                                                        <small class="text-body-secondary">1h ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <span class="avatar-initial rounded-circle bg-label-danger">CF</span>
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">Charles Franklin</h6>
                                                        <small class="mb-1 d-block text-body">Accepted your connection</small>
                                                        <small class="text-body-secondary">12hr ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                            <li class="list-group-item list-group-item-action dropdown-notifications-item marked-as-read">
                                                <div class="d-flex">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar">
                                                            <img src="../../assets/img/avatars/2.png" alt="" class="rounded-circle">
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="small mb-0">New Message ✉️</h6>
                                                        <small class="mb-1 d-block text-body">You have new message from Natalie</small>
                                                        <small class="text-body-secondary">1h ago</small>
                                                    </div>
                                                    <div class="flex-shrink-0 dropdown-notifications-actions">
                                                        <a href="javascript:void(0)" class="dropdown-notifications-read"><span class="badge badge-dot"></span></a>
                                                        <a href="javascript:void(0)" class="dropdown-notifications-archive"><span class="icon-base bx bx-x"></span></a>
                                                    </div>
                                                </div>
                                            </li>
                                        </ul>

                                        <div class="ps__rail-x" style="left: 0px; bottom: 0px;">
                                            <div class="ps__thumb-x" tabindex="0" style="left: 0px; width: 0px;"></div>
                                        </div>
                                        <div class="ps__rail-y" style="top: 0px; right: 0px;">
                                            <div class="ps__thumb-y" tabindex="0" style="top: 0px; height: 0px;"></div>
                                        </div>
                                    </li>

                                    <li class="border-top">
                                        <div class="d-grid p-4">
                                            <a class="btn btn-primary btn-sm d-flex" href="javascript:void(0);">
                                                <small class="align-middle">View all notifications</small>
                                            </a>
                                        </div>
                                    </li>
                                </ul> <!-- termina submenu de notificaciones -->
                            </li>




                            <!-- User -->
                            <li class="nav-item navbar-dropdown dropdown-user dropdown">
                                <a class="nav-link dropdown-toggle hide-arrow" href="javascript:void(0);" data-bs-toggle="dropdown">
                                    <div class="avatar avatar-online">
                                        <span class="avatar-initial rounded-circle bg-label-primary"><?php echo htmlspecialchars($inicialesUsuario); ?></span>
                                    </div>
                                </a>
                                <ul class="dropdown-menu dropdown-menu-end">
                                    <li>
                                        <a class="dropdown-item" href="#">
                                            <div class="d-flex">
                                                <div class="flex-shrink-0 me-3">
                                                    <div class="avatar avatar-online">
                                                        <span class="avatar-initial rounded-circle bg-label-primary"><?php echo htmlspecialchars($inicialesUsuario); ?></span>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <span class="fw-semibold d-block"><?php echo htmlspecialchars($nombre); ?></span>
                                                    <small class="text-muted"><?php echo htmlspecialchars($rol); ?></small>
                                                </div>
                                            </div>
                                        </a>
                                    </li>
                                    <li>
                                        <div class="dropdown-divider"></div>
                                    </li>
                                    <li>
                                        <a class="dropdown-item" href="index.html">
                                            <i class="bx bx-power-off me-2"></i>
                                            <span class="align-middle">Cerrar Sesión</span>
                                        </a>
                                    </li>
                                </ul>
                            </li>
                            <!--/ User -->
                        </ul>
                    </div>
                </nav>
                <!-- / Navbar -->
                <?php
                // Configuración de conexión a Firebird con PDO
                $host = 'localhost';
                $database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\SAE7.00\Ejemplos\Ejemplos.FDB';
                $username = 'SYSDBA';
                $password = 'masterkey';

                try {
                    $dbh = new PDO("firebird:dbname=$host:$database;charset=UTF8", $username, $password);
                    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                    // Consulta para obtener los clientes
                    $query = "SELECT NOMBRE, RFC, TELEFONO, ESTADO, MUNICIPIO, COLONIA FROM CLIE01";
                    $stmt = $dbh->prepare($query);
                    $stmt->execute();
                    $clientes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                } catch (PDOException $e) {
                    die("Error de conexión: " . $e->getMessage());
                }
                ?>
                <!-- Content wrapper -->
                <div class="content-wrapper">
                    <!-- Content -->
                    <div class="container-xxl flex-grow-1 container-p-y">
                        <div class="card mb-6 wow animate__animated animate__fadeInUp" data-wow-delay="0.8s">
                            <h5 class="card-header">Orden de Servicio<span class="text-primary"> Mantenimiento</span></h5>
                            <form class="card-body" id="formServicio" action="insertar_servicio.php" method="POST" accept-charset="UTF-8">
                                <h6>1. Detalles Cliente</h6>
                                <div class="row g-6">
                                    <div class="col-md-5">
                                        <label class="form-label" for="nombre">Nombre:</label>
                                        <select class="form-control" id="nombre" name="nombre" onchange="actualizarDatos()" required>
                                            <option value="">Seleccione un cliente</option>
                                            <?php foreach ($clientes as $cliente): ?>
                                                <option value="<?= htmlspecialchars($cliente['NOMBRE']) ?>"><?= htmlspecialchars($cliente['NOMBRE']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label" for="rfc">RFC:</label>
                                        <input class="form-control" type="text" id="rfc" name="rfc" required readonly>
                                    </div>

                                    <div class="col-md-4">
                                        <label class="form-label" for="telefono">Teléfono:</label>
                                        <input class="form-control" type="tel" id="telefono" name="telefono" required readonly>
                                    </div>


                                    <div class="col-md-4">
                                        <label class="form-label" for="estado">Estado:</label>
                                        <input class="form-control" type="text" id="estado" name="estado" required readonly>
                                    </div>

                                    <div class="col-md-4">
                                        <label class="form-label" for="municipio">Municipio:</label>
                                        <input class="form-control" type="text" id="municipio" name="municipio" required readonly>
                                    </div>

                                    <div class="col-md-4">
                                        <label class="form-label" for="colonia">Colonia:</label>
                                        <input class="form-control" type="text" id="colonia" name="colonia" required readonly>
                                    </div>
                                </div>


                                <hr class="my-6 mx-n6">
                                <h6>2. Detalles de la Orden</h6>
                                <div class="row g-6">
                                    <div class="col-md-4">
                                        <label class="form-label" for="tecnico">Técnico Asignado:</label>
                                        <select class="form-control" id="tecnico" name="tecnico[]" multiple required>
                                            <option value="">Seleccione un técnico</option>
                                            <?php
                                            // Conexión a la base de datos
                                            $conn = new mysqli('localhost', 'root', 'root', 'TRAX');

                                            if ($conn->connect_error) {
                                                die("Conexión fallida: " . $conn->connect_error);
                                            }
                                            // Obtener técnicos de la base de datos
                                            $sql = "SELECT CVE_TECNICO, NOMBRE FROM TECNICOS";
                                            $result = $conn->query($sql);

                                            if ($result->num_rows > 0) {
                                                while ($row = $result->fetch_assoc()) {
                                                    echo "<option value='" . $row['CVE_TECNICO'] . "'>" . htmlspecialchars($row['NOMBRE']) . "</option>";
                                                }
                                            }
                                            $conn->close();
                                            ?>
                                        </select>
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label" for="fecha">Selecciona una fecha:</label>
                                        <input type="date" id="fecha" name="fecha" class="form-control" placeholder="Selecciona una fecha" />
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label" for="hora">Hora del servicio:</label>
                                        <input class="form-control" type="time" id="hora" name="hora" min="09:00" max="17:00" step="900">
                                    </div>

                                    <div>
                                        <input type="checkbox" id="diaCompleto">
                                        <label for="diaCompleto">Servicio de todo el día</label>
                                    </div>

                                    <div id="horarioError" style="display:none; color:red; margin-top:5px;">
                                        Este horario ya está ocupado para alguno de los técnicos seleccionados.
                                    </div>

                                    <div class="col-md-2">
                                        <label class="form-label" for="factura">Su factura:</label>
                                        <input class="form-control" type="text" id="factura" name="factura" class="factura" placeholder="Clave factura" />
                                    </div>

                                    <div class="divider divider-dashed">
                                        <div class="divider-text">Servicios</div>
                                    </div>
                                </div>


                                <!-- Contenedor de partidas -->
                                <div id="acordeonPartidas">
                                    <div class="row g-6 partida mb-3">
                                        <div class="col-md-1">
                                            <label class="form-label">Partida</label>
                                            <input type="text" class="form-control partida-num" name="partida[]" value="1" readonly>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label" for="cantidad[]">Cantidad:</label>
                                            <input class="form-control" type="number" name="cantidad[]" required step="1">
                                        </div>
                                        <div class="col-md-9">
                                            <label class="form-label" for="servicio[]">Servicio:</label>
                                            <input class="form-control" type="text" name="servicio[]" required>
                                        </div>

                                        <div class="col-md-1">
                                            <label class="form-label" for="precio_unitario[]">Precio Unitario:</label>
                                            <input class="form-control" type="number" name="precio_unitario[]" required step="0.01">
                                        </div>

                                        <div class="col-md-12">
                                            <label class="form-label" for="observaciones[]">Observaciones:</label>
                                            <input class="form-control" name="observaciones[]" rows="2"></inputs>
                                        </div>
                                        <!-- <div class="col-md-6">
                                            <button class="btn btn-primary" type="button" onclick="eliminarPartida(this)">Eliminar</button>
                                        </div> -->
                                    </div>
                                </div>


                                <div class="row g-6">
                                    <div class="card-header mt-6 sticky-element bg-label-secondary d-flex justify-content-sm-between align-items-sm-center flex-column flex-sm-row ">
                                        <div class="col-md-6">
                                            <button class="btn btn-primary" type="button" onclick="agregarPartida()">Agregar Servicio</button>
                                        </div>

                                        <div class="col-md-6">
  <button id="btnEnviar" class="btn btn-primary" type="submit">
    Enviar
  </button>
</div>

                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-- Overlay -->
                    <div class="layout-overlay layout-menu-toggle"></div>
                </div>
                <!-- / Layout wrapper -->


                <script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>
                <script>
                    new WOW().init();
                </script>

                <!-- Core JS -->
                <!-- build:js assets/vendor/js/core.js -->
                <script src="../assets/vendor/libs/jquery/jquery.js"></script>
                <script src="../assets/vendor/libs/popper/popper.js"></script>
                <script src="../assets/vendor/js/bootstrap.js"></script>
                <script src="../assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>

                <script src="../assets/vendor/js/menu.js"></script>
                <!-- endbuild -->

                <!-- Vendors JS -->
                <script src="../assets/vendor/libs/apex-charts/apexcharts.js"></script>
                <!-- <script src="../assets/vendor/libs/sweetalert2/sweetalert2.js" aria-hidden="true"></script> -->

                <!-- Main JS -->
                <script src="../assets/js/main.js"></script>

                <!-- Page JS -->
                <script src="../assets/js/dashboards-analytics.js"></script>

                <!-- Place this tag in your head or just before your close body tag. -->
                <script async defer src="https://buttons.github.io/buttons.js"></script>


                <!-- Modal  -->
                <div class="modal fade" id="modalConfirmacion" tabindex="-1" aria-labelledby="modalConfirmacionLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h1 class="modal-title fs-5" id="modalConfirmacionLabel">Confirmación</h1>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                            </div>
                            <div class="modal-body" id="modalMensaje">
                                <!-- Aquí se pondrá el mensaje desde JS -->
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Aceptar</button>
                            </div>
                        </div>
                    </div>
                </div>

</body>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>


<script>
    document.addEventListener("DOMContentLoaded", function() {
        var modalConfirmacion = document.getElementById('modalConfirmacion');
        var form = document.getElementById('formServicio');

        modalConfirmacion.addEventListener('hidden.bs.modal', function() {
            console.log("Modal cerrada - reseteando formulario y select múltiple");

            form.reset(); // limpia los campos básicos

            // Limpia manualmente el select multiple
            var tecnicoSelect = document.getElementById("tecnico");
            if (tecnicoSelect) {
                for (let i = 0; i < tecnicoSelect.options.length; i++) {
                    tecnicoSelect.options[i].selected = false;
                }
                // Si usas un plugin para estilizar, aquí tendrías que actualizarlo
                console.log("Select múltiple limpiado");
            }
        });
    });
</script>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var modalConfirmacion = document.getElementById('modalConfirmacion');
        var form = document.getElementById('formServicio');

        // Espera a que la modal se cierre completamente (evento de Bootstrap)
        modalConfirmacion.addEventListener('hidden.bs.modal', function() {
            form.reset(); // Limpia el formulario
        });
    });
</script>

<script>
const form = document.getElementById('formServicio');
const btnEnviar = document.getElementById('btnEnviar');
const modalEl = document.getElementById('modalConfirmacion');

form.addEventListener('submit', function(e) {
    e.preventDefault(); // evitar envío normal

    // 🔹 Mostrar spinner y desactivar botón
    btnEnviar.disabled = true;
    btnEnviar.innerHTML = `
        <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
        Cargando...
    `;

    const formData = new FormData(this);

    fetch('insertar_servicio.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById('modalMensaje').innerHTML = data;

        const myModal = new bootstrap.Modal(modalEl);
        myModal.show();

        // 🔹 Restaurar el botón inmediatamente después de mostrar la modal
        btnEnviar.disabled = false;
        btnEnviar.innerHTML = 'Enviar';
    })
    .catch(error => {
        alert('Error en el envío: ' + error);

        // Restaurar botón si hay error
        btnEnviar.disabled = false;
        btnEnviar.innerHTML = 'Enviar';
    });
});
</script>



<script>
    $(document).ready(function() {
        $('#tecnico').select2({
            placeholder: "Seleccione uno o varios técnicos"
        });
    });
</script>

<!-- <script>
    // Inicializamos Flatpickr en el campo de fecha
    function inicializarCalendario(tecnicoId) {
        fetch('verificar_horario.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'tecnico=' + tecnicoId
            })
            .then(response => response.json())
            .then(fechasOcupadas => {
                console.log('Fechas ocupadas:', fechasOcupadas);

                // Configurar Flatpickr
                flatpickr(".fecha", {
                    dateFormat: "Y-m-d",
                    minDate: "today",
                    defaultDate: "today",
                    locale: "es",
                    disable: fechasOcupadas.map(fecha => ({
                        from: fecha,
                        to: fecha
                    })),
                    onDayCreate: function(dObj, dStr, fp, dayElem) {
                        if (fechasOcupadas.includes(dayElem.dateObj.toISOString().split('T')[0])) {
                            dayElem.classList.add('disabled-date');
                        }
                    }
                });
            })
            .catch(error => {
                console.error("Error al obtener fechas ocupadas:", error);
            });
    }

    // Llamada inicial al cargar la página (Cambia el técnicoId según lo necesites)
    document.addEventListener('DOMContentLoaded', function() {
        const tecnicoId = document.getElementById('tecnico').value || 1;
        inicializarCalendario(tecnicoId);
    });

    // Actualizar el calendario si se cambia el técnico
    document.getElementById('tecnico').addEventListener('change', function() {
        const tecnicoId = this.value;
        inicializarCalendario(tecnicoId);
    });
</script> -->


<script>
    const fechaInput = document.getElementById("fecha");
    const horaInput = document.getElementById("hora");
    const tecnicoSelect = document.getElementById("tecnico");
    const diaCompletoCheckbox = document.getElementById("diaCompleto");
    const errorDiv = document.getElementById("horarioError");

    fechaInput.addEventListener("change", verificarDisponibilidad);
    horaInput.addEventListener("change", verificarDisponibilidad);
    tecnicoSelect.addEventListener("change", verificarDisponibilidad);
    diaCompletoCheckbox.addEventListener("change", function() {
        // Si se activa el checkbox, deshabilitar hora
        horaInput.disabled = diaCompletoCheckbox.checked;
        verificarDisponibilidad();
    });

    function verificarDisponibilidad() {
        let fecha = fechaInput.value;
        let hora = horaInput.value;
        let tecnicos = Array.from(tecnicoSelect.selectedOptions).map(option => option.value).filter(val => val !== "");

        if (!fecha || tecnicos.length === 0 || (!hora && !diaCompletoCheckbox.checked)) return;

        let formData = new FormData();
        formData.append("fecha", fecha);
        formData.append("diaCompleto", diaCompletoCheckbox.checked ? "1" : "0");

        if (!diaCompletoCheckbox.checked) {
            formData.append("hora", hora);
        }

        tecnicos.forEach(tecnico => {
            formData.append("tecnicos[]", tecnico);
        });

        fetch("verificar_horario.php", {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.disponible) {
                    errorDiv.style.display = "none";
                } else {
                    errorDiv.style.display = "block";
                    if (!diaCompletoCheckbox.checked) {
                        horaInput.value = "";
                    }
                }
            })
            .catch(error => {
                console.error("Error al verificar el horario:", error);
            });
    }
</script>

<script>
    document.getElementById("formServicio").addEventListener("submit", function(event) {
        event.preventDefault(); // Evita la recarga
        let fecha = document.getElementById("fecha").value;
        let servicio = document.getElementById("servicio").value;

        if (fecha && servicio) {
            let evento = {
                title: servicio,
                start: fecha
            };
            localStorage.setItem("eventoGuardado", JSON.stringify(evento));

            // Redirigir al calendario para que lo muestre
            window.location.href = "calendario.html";
        }
    });
</script>

<script>
    function actualizarDatos() {
        let clientes = <?php echo json_encode($clientes); ?>;
        let seleccion = document.getElementById("nombre").value;
        let rfcInput = document.getElementById("rfc");
        let telefonoInput = document.getElementById("telefono");
        let estadoInput = document.getElementById("estado");
        let municipioInput = document.getElementById("municipio");
        let coloniaInput = document.getElementById("colonia");

        let clienteSeleccionado = clientes.find(cliente => cliente.NOMBRE === seleccion);
        if (clienteSeleccionado) {
            rfcInput.value = clienteSeleccionado.RFC;
            telefonoInput.value = clienteSeleccionado.TELEFONO;
            estadoInput.value = clienteSeleccionado.ESTADO;
            municipioInput.value = clienteSeleccionado.MUNICIPIO;
            coloniaInput.value = clienteSeleccionado.COLONIA;
        } else {
            rfcInput.value = "";
            telefonoInput.value = "";
            estadoInput.value = "";
            municipioInput.value = "";
            coloniaInput.value = "";
        }
    }
</script>


<script>
    let contadorPartidas = 1;

    function agregarPartida() {
        contadorPartidas++;

        const partida = document.createElement('div');
        partida.classList.add('row', 'g-6', 'partida', 'mb-3');
        partida.innerHTML = `
            <hr>
            <div class="col-md-1">
                <label class="form-label">Partida</label>
                <input type="text" class="form-control partida-num" name="partida[]" readonly>
            </div>
            <div class="col-md-1">
                <label class="form-label">Cantidad:</label>
                <input class="form-control" type="number" name="cantidad[]" required step="1">
            </div>
            <div class="col-md-9">
                <label class="form-label">Servicio:</label>
                <input class="form-control" type="text" name="servicio[]" required>
            </div>
            <div class="col-md-1">
                <label class="form-label">Precio Unitario:</label>
                <input class="form-control" type="number" name="precio_unitario[]" required step="0.01">
            </div>
            <div class="col-md-12">
                <label class="form-label">Observaciones:</label>
                <textarea class="form-control" name="observaciones[]" rows="1"></textarea>
            </div>
            <div class="col-md-12 text-end">
                <button class="btn btn-danger mt-2" type="button" onclick="eliminarPartida(this)">Eliminar</button>
            </div>
        `;

        document.getElementById('acordeonPartidas').appendChild(partida);
        actualizarNumerosPartida(); //  cada vez que se agrega
    }

    function eliminarPartida(boton) {
        const partida = boton.closest('.partida');
        if (partida) partida.remove();
        actualizarNumerosPartida(); //  reenumerar después de eliminar
    }

    function actualizarNumerosPartida() {
        const partidas = document.querySelectorAll('.partida');
        partidas.forEach((p, index) => {
            const inputNum = p.querySelector('.partida-num');
            if (inputNum) inputNum.value = index + 1;
        });
        contadorPartidas = partidas.length; // sincroniza el contador
    }
</script>



</html>