<?php
session_start();
include '../../script/conexion.php';
require '../general/validacion.php';

date_default_timezone_set('America/Bogota');

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function nf0($value)
{
    return number_format((float)$value, 0, ',', '.');
}

$q = trim($_GET['q'] ?? '');
$qSql = $conn->real_escape_string($q);

$where = "1=1";
if ($q !== '') {
    $where .= " AND (
        nit LIKE '%$qSql%' OR
        nombre LIKE '%$qSql%' OR
        telefono LIKE '%$qSql%' OR
        direccion LIKE '%$qSql%'
    )";
}

/*
|--------------------------------------------------------------------------
| Estadísticas
|--------------------------------------------------------------------------
*/
$stats = [
    'total'         => 0,
    'con_nit'       => 0,
    'con_telefono'  => 0,
    'con_direccion' => 0,
];

$sqlStats = "
    SELECT
        COUNT(*) AS total,
        SUM(CASE WHEN nit IS NOT NULL AND nit <> '' AND nit <> 'Opcional' THEN 1 ELSE 0 END) AS con_nit,
        SUM(CASE WHEN telefono IS NOT NULL AND telefono <> '' THEN 1 ELSE 0 END) AS con_telefono,
        SUM(CASE WHEN direccion IS NOT NULL AND direccion <> '' THEN 1 ELSE 0 END) AS con_direccion
    FROM alm_tercero
    WHERE $where
";
$queryStats = $conn->query($sqlStats);
if ($queryStats && $queryStats->num_rows > 0) {
    $rowStats = $queryStats->fetch_assoc();
    $stats['total']         = (int)($rowStats['total'] ?? 0);
    $stats['con_nit']       = (int)($rowStats['con_nit'] ?? 0);
    $stats['con_telefono']  = (int)($rowStats['con_telefono'] ?? 0);
    $stats['con_direccion'] = (int)($rowStats['con_direccion'] ?? 0);
}

/*
|--------------------------------------------------------------------------
| Lista
|--------------------------------------------------------------------------
*/
$terceros = [];
$sql = "SELECT * FROM alm_tercero WHERE $where ORDER BY nombre ASC";
$query = $conn->query($sql);
if ($query && $query->num_rows > 0) {
    while ($row = $query->fetch_assoc()) {
        $terceros[] = $row;
    }
}
?>
<!doctype html>
<html lang="es" class="light-theme">
<head>
    <?php include '../general/libreria-css.php'; ?>

    <style>
        :root {
            --page-bg: #f6f8fb;
            --card-bg: #ffffff;
            --text-main: #1f2937;
            --text-soft: #6b7280;
            --line: #e5e7eb;
            --primary: #111827;
            --primary-soft: rgba(17, 24, 39, .06);
            --success-soft: rgba(34, 197, 94, .12);
            --warning-soft: rgba(245, 158, 11, .12);
            --danger-soft: rgba(239, 68, 68, .12);
            --info-soft: rgba(59, 130, 246, .12);
            --shadow: 0 10px 30px rgba(15, 23, 42, .06);
            --radius: 18px;
        }

        body {
            background: var(--page-bg);
            color: var(--text-main);
        }

        .page-title-card,
        .form-card,
        .stats-card,
        .list-card {
            border: 0;
            border-radius: var(--radius);
            background: var(--card-bg);
            box-shadow: var(--shadow);
        }

        .page-title-card .card-body,
        .form-card .card-body,
        .list-card .card-body {
            padding: 1.25rem 1.35rem;
        }

        .page-title-main {
            font-size: 1.55rem;
            font-weight: 800;
            margin-bottom: .2rem;
            letter-spacing: .2px;
        }

        .page-subtitle {
            color: var(--text-soft);
            margin: 0;
            font-size: .95rem;
        }

        .page-badges {
            display: flex;
            gap: .5rem;
            flex-wrap: wrap;
            margin-top: .8rem;
        }

        .info-chip {
            display: inline-flex;
            align-items: center;
            gap: .35rem;
            padding: .45rem .75rem;
            border-radius: 999px;
            background: #f8fafc;
            border: 1px solid var(--line);
            font-size: .82rem;
            color: var(--text-main);
            font-weight: 600;
        }

        .stats-card .card-body {
            padding: 1rem 1.1rem;
        }

        .stats-icon {
            width: 44px;
            height: 44px;
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-soft);
            color: var(--primary);
            font-size: 1.05rem;
            margin-bottom: .85rem;
        }

        .stats-title {
            font-size: .78rem;
            color: var(--text-soft);
            text-transform: uppercase;
            letter-spacing: .08em;
            margin-bottom: .35rem;
            font-weight: 700;
        }

        .stats-value {
            font-size: 1.35rem;
            font-weight: 800;
            line-height: 1.1;
            color: var(--text-main);
        }

        .stats-note {
            font-size: .8rem;
            color: var(--text-soft);
            margin-top: .35rem;
        }

        .section-head {
            display: flex;
            justify-content: space-between;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 1rem;
        }

        .section-title {
            font-size: 1rem;
            font-weight: 800;
            margin-bottom: .15rem;
        }

        .section-subtitle {
            color: var(--text-soft);
            font-size: .88rem;
            margin: 0;
        }

        .label-soft {
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            color: var(--text-soft);
            font-weight: 700;
            margin-bottom: .45rem;
        }

        .btn-modern {
            border-radius: 12px;
            padding: .72rem 1rem;
            font-weight: 800;
        }

        .table-modern {
            margin-bottom: 0;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table-modern thead th {
            background: #f8fafc;
            color: #334155;
            font-size: .78rem;
            text-transform: uppercase;
            letter-spacing: .08em;
            font-weight: 800;
            border-bottom: 1px solid var(--line);
            border-top: 0;
            white-space: nowrap;
            padding: .8rem .65rem;
        }

        .table-modern tbody td {
            padding: .82rem .65rem;
            vertical-align: middle;
            border-color: #eef2f7;
        }

        .table-modern tbody tr:hover {
            background: #fafcff;
        }

        .name-main {
            font-weight: 800;
            color: #111827;
        }

        .text-soft-mini {
            color: var(--text-soft);
            font-size: .82rem;
        }

        .action-btn {
            width: 38px;
            height: 38px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            border: 1px solid #e5e7eb;
            background: #fff;
            transition: all .18s ease;
        }

        .action-btn:hover {
            transform: translateY(-1px);
        }

        .action-edit {
            color: #b45309;
        }

        .action-edit:hover {
            background: rgba(245, 158, 11, .10);
            border-color: rgba(245, 158, 11, .35);
            color: #b45309;
        }

        .action-delete {
            color: #b91c1c;
        }

        .action-delete:hover {
            background: rgba(239, 68, 68, .10);
            border-color: rgba(239, 68, 68, .35);
            color: #b91c1c;
        }

        .modal-content {
            border: 0;
            border-radius: 18px;
            overflow: hidden;
        }

        .modal-header-edit {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: #fff;
        }

        .modal-header-delete {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: #fff;
        }

        .empty-state {
            border: 1px dashed #cbd5e1;
            border-radius: 18px;
            padding: 2rem 1rem;
            text-align: center;
            background: #fff;
        }

        .empty-state i {
            font-size: 2rem;
            color: #94a3b8;
            margin-bottom: .75rem;
        }

        .empty-state h5 {
            font-weight: 800;
            margin-bottom: .35rem;
        }

        .empty-state p {
            color: var(--text-soft);
            margin-bottom: 0;
        }

        @media print {
            .d-print-none,
            .wrapper aside,
            .top-header,
            .modal {
                display: none !important;
            }

            body {
                background: #fff !important;
            }

            .page-title-card,
            .form-card,
            .stats-card,
            .list-card {
                box-shadow: none !important;
                border: 1px solid #ddd !important;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php echo include '../general/menu.php'; ?>

        <div class="page-content-wrapper">
            <div class="page-content">

                <nav aria-label="breadcrumb" class="mb-3 d-print-none">
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item">
                            <a href="../inicio/inicio.php">
                                <ion-icon name="home-outline"></ion-icon>
                            </a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Terceros</li>
                    </ol>
                </nav>

                <div class="card page-title-card mb-3">
                    <div class="card-body">
                        <div class="page-title-main">Terceros</div>
                        <p class="page-subtitle">
                            Gestión de clientes y terceros del almacén, con búsqueda rápida, creación y edición centralizada.
                        </p>

                        <div class="page-badges">
                            <span class="info-chip">
                                <i class="fas fa-users"></i>
                                Registros: <?= nf0($stats['total']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-id-card"></i>
                                Con NIT: <?= nf0($stats['con_nit']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-phone"></i>
                                Con teléfono: <?= nf0($stats['con_telefono']) ?>
                            </span>
                            <span class="info-chip">
                                <i class="fas fa-location-dot"></i>
                                Con dirección: <?= nf0($stats['con_direccion']) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-users"></i></div>
                                <div class="stats-title">Terceros</div>
                                <div class="stats-value"><?= nf0($stats['total']) ?></div>
                                <div class="stats-note">Total según filtro aplicado</div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-id-card"></i></div>
                                <div class="stats-title">Con NIT</div>
                                <div class="stats-value"><?= nf0($stats['con_nit']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-phone"></i></div>
                                <div class="stats-title">Con teléfono</div>
                                <div class="stats-value"><?= nf0($stats['con_telefono']) ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6 col-xl-3">
                        <div class="card stats-card h-100">
                            <div class="card-body">
                                <div class="stats-icon"><i class="fas fa-location-dot"></i></div>
                                <div class="stats-title">Con dirección</div>
                                <div class="stats-value"><?= nf0($stats['con_direccion']) ?></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-3">
                    <div class="col-xl-4">
                        <div class="card form-card">
                            <div class="card-body">
                                <div class="section-title">Nuevo tercero</div>
                                <p class="section-subtitle">
                                    Registra un nuevo tercero con su información principal.
                                </p>

                                <form class="row g-3" method="POST" action="script/tercero-guardar.php">
                                    <div class="col-md-4">
                                        <label class="label-soft">NIT</label>
                                        <input class="form-control" type="text" required name="nit" value="Opcional">
                                    </div>

                                    <div class="col-md-8">
                                        <label class="label-soft">Nombre</label>
                                        <input class="form-control" type="text" required name="nombre">
                                    </div>

                                    <div class="col-md-4">
                                        <label class="label-soft">Teléfono</label>
                                        <input class="form-control" type="text" required name="telefono">
                                    </div>

                                    <div class="col-md-8">
                                        <label class="label-soft">Dirección</label>
                                        <input class="form-control" type="text" required name="direccion">
                                    </div>

                                    <div class="col-md-12 text-end">
                                        <button type="submit" class="btn btn-dark btn-modern">
                                            <i class="fas fa-save me-1"></i> Guardar
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-xl-8">
                        <div class="card list-card">
                            <div class="card-body">
                               

                                <?php if (empty($terceros)): ?>
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <h5>Sin resultados</h5>
                                        <p>No se encontraron terceros con el filtro actual.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-modern align-middle table-striped table-bordered" id="example2">
                                            <thead>
                                                <tr>
                                                    <th class="text-center">NIT</th>
                                                    <th>Nombre</th>
                                                    <th>Teléfono</th>
                                                    <th>Dirección</th>
                                                    <th class="text-center">Acciones</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($terceros as $row): ?>
                                                    <tr>
                                                        <td class="text-center"><?= h($row['nit']) ?></td>
                                                        <td>
                                                            <div class="name-main"><?= h($row['nombre']) ?></div>
                                                        </td>
                                                        <td><?= h($row['telefono']) ?></td>
                                                        <td>
                                                            <span class="text-soft-mini"><?= h($row['direccion']) ?></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <button
                                                                type="button"
                                                                class="action-btn action-edit"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#editarModal"
                                                                data-id="<?= h($row['id']) ?>"
                                                                data-nit="<?= h($row['nit']) ?>"
                                                                data-nombre="<?= h($row['nombre']) ?>"
                                                                data-telefono="<?= h($row['telefono']) ?>"
                                                                data-direccion="<?= h($row['direccion']) ?>"
                                                                title="Editar"
                                                            >
                                                                <i class="far fa-edit"></i>
                                                            </button>

                                                            <button
                                                                type="button"
                                                                class="action-btn action-delete ms-2"
                                                                data-bs-toggle="modal"
                                                                data-bs-target="#eliminarModal"
                                                                data-id="<?= h($row['id']) ?>"
                                                                data-nombre="<?= h($row['nombre']) ?>"
                                                                title="Eliminar"
                                                            >
                                                                <i class="far fa-trash-alt"></i>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>

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

                <?php echo include '../general/footer.php'; ?>
            </div>
        </div>
    </div>

    <div class="modal fade" id="editarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header modal-header-edit">
                    <h5 class="modal-title mb-0">Editar tercero</h5>
                    <button type="button" class="btn-close btn-close-white shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/tercero-editar.php">
                    <input type="hidden" name="id" id="editar_id">

                    <div class="modal-body p-4">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="label-soft">NIT</label>
                                <input class="form-control" type="text" required name="nit" id="editar_nit">
                            </div>

                            <div class="col-md-8">
                                <label class="label-soft">Nombre</label>
                                <input class="form-control" type="text" required name="nombre" id="editar_nombre">
                            </div>

                            <div class="col-md-4">
                                <label class="label-soft">Teléfono</label>
                                <input class="form-control" type="text" required name="telefono" id="editar_telefono">
                            </div>

                            <div class="col-md-8">
                                <label class="label-soft">Dirección</label>
                                <input class="form-control" type="text" required name="direccion" id="editar_direccion">
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer px-4 pb-4 border-0">
                        <button type="button" class="btn btn-outline-secondary btn-modern" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-dark btn-modern">Guardar cambios</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="eliminarModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header modal-header-delete">
                    <h5 class="modal-title mb-0">Eliminar tercero</h5>
                    <button type="button" class="btn-close btn-close-white shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <form method="POST" action="script/tercero-eliminar.php">
                    <input type="hidden" name="id" id="eliminar_id">

                    <div class="modal-body p-4">
                        <p class="mb-0">
                            ¿Seguro deseas eliminar el tercero
                            <strong id="eliminar_nombre"></strong>?
                        </p>
                    </div>

                    <div class="modal-footer px-4 pb-4 border-0">
                        <button type="button" class="btn btn-outline-secondary btn-modern" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-danger btn-modern">Eliminar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php echo include '../general/libreria-js.php'; ?>


  <script>
            //Tabla producto
            $(document).ready(function () {
                var table = $('#example2').DataTable({
                    lengthChange: false,
                    buttons: ['copy', 'excel', 'pdf', 'print'],
                    "order": false,
                });

                table.buttons().container()
                        .appendTo('#example2_wrapper .col-md-6:eq(0)');
            });

        </script>

    <script>
        const editarModal = document.getElementById('editarModal');
        if (editarModal) {
            editarModal.addEventListener('show.bs.modal', function (event) {
                const button = event.relatedTarget;

                document.getElementById('editar_id').value = button.getAttribute('data-id') || '';
                document.getElementById('editar_nit').value = button.getAttribute('data-nit') || '';
                document.getElementById('editar_nombre').value = button.getAttribute('data-nombre') || '';
                document.getElementById('editar_telefono').value = button.getAttribute('data-telefono') || '';
                document.getElementById('editar_direccion').value = button.getAttribute('data-direccion') || '';
            });
        }

        const eliminarModal = document.getElementById('eliminarModal');
        if (eliminarModal) {
            eliminarModal.addEventListener('show.bs.modal', function (event) {
                const button = event.relatedTarget;

                document.getElementById('eliminar_id').value = button.getAttribute('data-id') || '';
                document.getElementById('eliminar_nombre').textContent = button.getAttribute('data-nombre') || '';
            });
        }
    </script>
</body>
</html>