<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Outbound Goods List</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link rel="icon" href="<?= base_url('asset/img/asiaserv-logo.png') ?>" type="image/png">

    <style>
        :root {
            --primary-color: #dc3545; /* Red (Danger) */
            --dark-header: #2c3e50; /* Darker tone for contrast */
            --bg-main: #f8f9fa; /* Lighter background color */
            --card-shadow: 0 10px 30px rgba(0,0,0,0.08);
        }

        body {
            background-color: var(--bg-main);
            font-family: 'Poppins', sans-serif;
            color: #343a40;
            padding-top: 20px;
        }

        .main-card {
            background-color: #fff;
            border-radius: 15px;
            box-shadow: var(--card-shadow);
            overflow: hidden; 
            margin-top: 20px;
            border: none;
        }

        .card-header-custom {
            background-color: var(--primary-color);
            color: #fff;
            padding: 20px 30px; 
            border-radius: 15px 15px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        h2 {
            margin: 0;
            font-weight: 700;
        }

        .toolbar-container {
            padding: 20px 30px 15px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .filters-group .form-control, .filters-group .btn {
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        #barangTable thead th {
            background-color: var(--dark-header) !important; 
            color: white;
            text-align: center;
            vertical-align: middle;
            font-weight: 600;
        }

        #barangTable tbody td {
            text-align: center;
            vertical-align: middle;
            font-size: 0.9rem;
            padding: 12px 8px;
        }

        #barangTable th,
#barangTable td {
    text-align: center !important;
    vertical-align: middle !important;
}

        #barangTable tbody tr:hover {
            background-color: #fef1f2 !important; 
        }
        
        /* === PHOTO PREVIEW ENHANCEMENTS === */
        .foto-barang {
            width: 70px; 
            height: 70px;
            object-fit: cover;
            border-radius: 8px; 
            cursor: pointer;
            border: 3px solid transparent;
            transition: border-color .3s, transform .3s, box-shadow .3s;
        }

        .foto-barang:hover {
            transform: scale(1.05);
            border-color: var(--primary-color);
            box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
        }
        /* PERBESAR FONT UNTUK HALAMAN OUTBOUND GOODS LIST */
#barangTable th,
#barangTable td {
    font-size: 20px !important;   /* kamu bisa ganti jadi 16 kalau mau lebih besar */
}

#barangTable td span.badge {
    font-size: 14px !important;
    padding: 6px 10px !important;
}

.card-header-custom h2 {
    font-size: 26px !important; /* judul card header besar */
}

.toolbar-container input.form-control,
.toolbar-container button,
.toolbar-container a.btn {
    font-size: 14px !important;
}

.btn-action {
    font-size: 13px !important;
    padding: 7px 12px !important;
}

        
        /* Modal Style */
        .modal-header-custom {
            background-color: var(--primary-color);
            color: white;
            border-bottom: none;
        }
        
        #previewFoto {
            max-width: 100%;
            height: auto;
            max-height: 80vh;
            border-radius: 10px;
            box-shadow: 0 10px 20px rgba(0,0,0,0.3);
        }

        .btn-action { 
            border-radius: 6px; 
            padding: 6px 10px;
            font-size: 0.8rem;
        }

        .card-footer {
            background: #f8f9fa;
            border-top: 1px solid #dee2e6;
            padding: 15px 30px;
            border-radius: 0 0 15px 15px;
        }

        #pagination button {
            margin: 0 2px;
            min-width: 38px;
        }
    </style>
</head>
<body class="py-4">

<div class="container-fluid">
<div class="main-card">
    <div class="card-header-custom">
        <h2><i class="fa fa-dolly me-2"></i>Outbound Goods List</h2>
        <a href="<?= site_url('barang_keluar_controller/create') ?>" class="btn btn-light shadow-sm d-flex align-items-center fw-bold">
            <i class="fa fa-plus me-1"></i> Add New Data
        </a>
    </div>

    <div class="toolbar-container">
        <div class="d-flex gap-3 flex-wrap align-items-center">
            <input type="text" id="searchInput" class="form-control" style="width: 280px;" placeholder="🔍 Search PIC/Driver/Destination...">
            <input type="date" id="filterTanggal" class="form-control" style="width: 150px;">
            <button class="btn btn-outline-danger" onclick="resetFilter()"><i class="fa fa-sync-alt"></i> Reset Filter</button>

            <div class="ms-auto d-flex gap-2">
                <a href="#" id="exportExcel" class="btn btn-success shadow-sm">
                    <i class="fa fa-file-excel me-1"></i> Export Excel
                </a>
                <a href="#" id="exportPDF" class="btn btn-danger shadow-sm">
                    <i class="fa fa-file-pdf me-1"></i> Export PDF
                </a>
            </div>
        </div>
    </div>

    <div class="card-body p-0 table-responsive">
        <table id="barangTable" class="table table-striped table-hover align-middle mb-0">
            <thead class="table-dark">
                <tr>
                    <th style="width: 5%;">NO</th>
                    <th>PIC</th>
                    <th>Item Type</th>
                    <th style="width: 8%;">Quantity</th>                  
                    <th>From</th>
                    <th>Destination</th>
                    <th style="width: 10%;">Date</th>
                    <th style="width: 10%;">Out Time</th>
                    <th style="width: 10%;">Photo</th>
                    <th style="width: 10%;">Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($barang_keluar)): ?>
                <?php $no=1; foreach($barang_keluar as $bk): ?>
                    <tr data-tanggal="<?= date('Y-m-d', strtotime($bk->tanggal)) ?>" 
                        data-pic="<?= strtolower($bk->pic) ?>" 
                         
                        data-tujuan="<?= strtolower($bk->tujuan) ?>">
                        <td><?= $no++ ?></td>
                        <td class="fw-medium"><?= $bk->pic ?></td>
                        <td><?= $bk->jenis_barang ?></td>
                        <td><span class="badge bg-primary rounded-pill px-3 py-2"><?= $bk->jumlah ?></span></td> 
                        <td><?= $bk->origin ?></td>
                        <td><?= $bk->tujuan ?></td>
                        <td><span class="badge bg-danger"><?= date('Y-m-d', strtotime($bk->tanggal)) ?></span></td>
                        <td><?= $bk->waktu_keluar ?></td>
                        <td>
                            <?php if(!empty($bk->foto) && file_exists(FCPATH.'uploads/'.$bk->foto)): ?>
                                <img src="<?= base_url('uploads/'.$bk->foto) ?>" alt="Item Photo" class="foto-barang" 
                                     data-bs-toggle="modal" data-bs-target="#fotoModal" data-src="<?= base_url('uploads/'.$bk->foto) ?>"
                                     title="Click to view photo">
                            <?php else: ?>
                                <span class="badge bg-secondary"><i class="fa fa-camera-slash me-1"></i> No Photo</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="d-flex justify-content-center gap-1">
                                <a href="<?= site_url('barang_keluar_controller/edit/'.$bk->id) ?>" class="btn btn-warning btn-action shadow-sm" title="Edit"><i class="fa fa-edit"></i> Edit</a>
                                
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr><td colspan="11" class="text-muted py-4"><i class="fa fa-info-circle me-1"></i> No outbound goods data available.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div> 

    <div class="card-footer d-flex justify-content-between align-items-center">
        <a href="<?= site_url('dashboard/user') ?>" class="btn btn-outline-secondary shadow-sm"><i class="fa fa-arrow-left me-1"></i> Back to Dashboard</a>
        <div id="pagination" class="d-flex gap-1"></div>
    </div>
</div>
</div>

<div class="modal fade" id="fotoModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-header modal-header-custom">
        <h5 class="modal-title">
          <i class="fa fa-truck-loading me-1"></i> Outbound Item Photo Preview
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center p-4 bg-light position-relative">
        <a id="downloadFotoBtn" href="#" download class="btn btn-success position-absolute" 
           style="top: 15px; right: 15px; z-index: 10;">
          <i class="fa fa-download me-1"></i> Download
        </a>

        <img id="previewFoto" src="" class="modal-img rounded shadow-lg" 
             alt="Item Photo" style="max-height: 75vh; width: auto;">
      </div>
    </div>
  </div>
</div>


<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/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<script>
const rowsPerPage = 12;
let currentPage = 1;

function applyFilterAndPaginate() {
    const filter = document.getElementById("searchInput").value.toLowerCase();
    const filterDate = document.getElementById("filterTanggal").value;
    const rows = document.querySelectorAll("#barangTable tbody tr");
    const filteredRows = [];

    rows.forEach(row => {
        // Retrieve data-attributes for specific searching
        const pic = row.getAttribute('data-pic') || '';
        const driver = row.getAttribute('data-driver') || '';
        const tujuan = row.getAttribute('data-tujuan') || '';
        const tanggal = row.getAttribute('data-tanggal');
        
        const matchSearch = filter === '' || pic.includes(filter) || driver.includes(filter) || tujuan.includes(filter);
        const matchDate = !filterDate || tanggal === filterDate;

        if (matchSearch && matchDate) filteredRows.push(row);
        else row.style.display = "none";
    });

    const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
    if (currentPage > totalPages) currentPage = Math.max(1, totalPages);

    filteredRows.forEach((row, i) => {
        row.style.display = (i >= (currentPage-1)*rowsPerPage && i < currentPage*rowsPerPage) ? "" : "none";
    });

    const pagination = document.getElementById("pagination");
    pagination.innerHTML = "";
    
    if (totalPages > 1) {
        const prevBtn = document.createElement("button");
        prevBtn.innerText = '«';
        prevBtn.className = "btn btn-sm btn-outline-danger";
        prevBtn.disabled = currentPage === 1;
        prevBtn.onclick = () => { currentPage--; applyFilterAndPaginate(); };
        pagination.appendChild(prevBtn);

        for (let i = 1; i <= totalPages; i++) {
            const btn = document.createElement("button");
            btn.className = "btn btn-sm " + (i===currentPage ? "btn-danger" : "btn-outline-danger");
            btn.textContent = i;
            btn.onclick = () => { currentPage = i; applyFilterAndPaginate(); };
            pagination.appendChild(btn);
        }
        
        const nextBtn = document.createElement("button");
        nextBtn.innerText = '»';
        nextBtn.className = "btn btn-sm btn-outline-danger";
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.onclick = () => { currentPage++; applyFilterAndPaginate(); };
        pagination.appendChild(nextBtn);
    }
}

document.getElementById("searchInput").addEventListener("keyup", () => { currentPage=1; applyFilterAndPaginate(); });
document.getElementById("filterTanggal").addEventListener("change", () => { currentPage=1; applyFilterAndPaginate(); });

function resetFilter() {
    document.getElementById("searchInput").value = "";
    document.getElementById("filterTanggal").value = "";
    currentPage = 1;
    applyFilterAndPaginate();
}

window.onload = applyFilterAndPaginate;

<?php if(isset($this->session) && $this->session->flashdata('success')): ?>
Swal.fire({ icon: 'success', title: 'Success!', text: '<?= $this->session->flashdata('success'); ?>', timer: 2000, showConfirmButton: false });
<?php endif; ?>

document.querySelectorAll('.btnDelete').forEach(btn=>{
    btn.addEventListener('click', e=>{
        e.preventDefault();
        const url = btn.dataset.url;
        Swal.fire({
            title: 'Are you sure you want to delete this data?',
            text: 'Deleted data cannot be recovered!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then(r=>{ if(r.isConfirmed) window.location.href=url; });
    });
});

document.getElementById('fotoModal').addEventListener('show.bs.modal', e=>{
    const imageSrc = e.relatedTarget.getAttribute('data-src');
    document.getElementById('previewFoto').src = imageSrc;
    document.getElementById('downloadFotoBtn').href = imageSrc;
    
    // Set filename for download
    const filename = imageSrc.substring(imageSrc.lastIndexOf('/')+1);
    document.getElementById('downloadFotoBtn').setAttribute('download', filename);
});

// Export based on current filter values
document.getElementById("exportExcel").addEventListener("click", function() {
    const s = document.getElementById("searchInput").value;
    const t = document.getElementById("filterTanggal").value;
    window.location.href = `<?= site_url('barang_keluar_controller/export_excel') ?>?search=${encodeURIComponent(s)}&tanggal=${encodeURIComponent(t)}`;
});
document.getElementById("exportPDF").addEventListener("click", function() {
    const s = document.getElementById("searchInput").value;
    const t = document.getElementById("filterTanggal").value;
    window.location.href = `<?= site_url('barang_keluar_controller/export_pdf') ?>?search=${encodeURIComponent(s)}&tanggal=${encodeURIComponent(t)}`;
});
</script>
</body>
</html>