<?php include 'header.php'; ?>
<!-- Vendors CSS -->
<link rel="stylesheet" href="assets/plugins/datatables/responsive.bootstrap5.min.css" />
<link rel="stylesheet" href="assets/plugins/datatables/buttons.bootstrap5.min.css" />
<style>
    .highlight-red {
        background-color: #ffcccc !important;
    }
</style>
<div class="wrapper">
    <?php require_once 'sidebar.php'; ?>
    <?php require_once 'topbar.php'; ?>

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

            <!-- Start Content-->
            <div class="px-0">

                <!-- Page Title -->
                <div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
                    <div class="flex-grow-1">
                        <h4 class="fs-18 fw-semibold m-0">Bulk Shipment Upload</h4>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h4 class="card-title">Upload Excel/CSV</h4>
                                <a href="api/shipment/download_template.php" class="btn btn-outline-primary btn-sm">
                                    <i class="ti ti-download"></i> Download Template
                                </a>
                            </div>
                            <div class="card-body">
                                <form id="uploadForm" enctype="multipart/form-data">
                                    <div class="row align-items-end">
                                        <div class="col-md-6">
                                            <label class="form-label">Select File (CSV/Excel)</label>
                                            <input type="file" class="form-control" name="bulk_file" required
                                                accept=".csv, .xlsx, .xls">
                                            <small class="text-muted">Ensure required columns are filled as per
                                                template.</small>
                                        </div>
                                        <div class="col-md-2">
                                            <button type="submit" class="btn btn-primary w-100" id="btnUpload">
                                                <i class="ti ti-upload"></i> Upload
                                            </button>
                                        </div>
                                    </div>
                                    <div id="uploadProgress" class="mt-3 d-none">
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar progress-bar-striped progress-bar-animated"
                                                role="progressbar" style="width: 100%">Processing...</div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Upload History</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table id="bulkJobsTable" class="table table-striped dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Job ID</th>
                                                <th>Date</th>
                                                <th>Original File</th>
                                                <th>Total</th>
                                                <th>Success</th>
                                                <th>Failed</th>
                                                <th>Status</th>
                                                <th>Result File</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Loaded via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

<!-- Vendors JS -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/datatables/dataTables.min.js"></script>
<script src="assets/plugins/datatables/dataTables.bootstrap5.min.js"></script>
<script src="assets/plugins/datatables/dataTables.responsive.min.js"></script>
<script src="assets/plugins/datatables/responsive.bootstrap5.min.js"></script>
<?php include 'footer.php'; ?>

<script>
    $(document).ready(function () {
        var table = $('#bulkJobsTable').DataTable({
            ajax: 'api/shipment/bulk_jobs_list.php',
            columns: [
                { data: 'id' },
                { data: 'created_at' },
                { data: 'filename' },
                { data: 'total_records' },
                { data: 'success_count', render: function (d) { return `<span class="text-success fw-bold">${d}</span>`; } },
                { data: 'failure_count', render: function (d) { return `<span class="text-danger fw-bold">${d}</span>`; } },
                {
                    data: 'status', render: function (d) {
                        let cls = 'bg-secondary';
                        if (d === 'Completed') cls = 'bg-success';
                        if (d === 'Processing') cls = 'bg-warning text-dark';
                        return `<span class="badge ${cls}">${d}</span>`;
                    }
                },
                {
                    data: 'id', render: function (id, type, row) {
                        let html = '';
                        if (row.status === 'Completed' && row.success_count > 0) {
                            html += `<a href="shipment-bulk-print.php?job_id=${id}" class="btn btn-sm btn-warning" target="_blank">
                                <i class="ti ti-printer"></i> Print Labels
                            </a> `;
                        }
                        if (row.result_file) html += `<a href="api/shipment/export_result.php?id=${id}" class="btn btn-sm btn-info" download>Download Result</a>`;
                        return html || '-';
                    }
                }
            ],
            order: [[0, 'desc']]
        });

        $('#uploadForm').on('submit', function (e) {
            e.preventDefault();
            var formData = new FormData(this);

            $('#btnUpload').prop('disabled', true);
            $('#uploadProgress').removeClass('d-none');

            $.ajax({
                url: 'api/shipment/bulk_upload.php',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#btnUpload').prop('disabled', false);
                    $('#uploadProgress').addClass('d-none');

                    if (response.status === 'success') {
                        alert('Upload Success! ' + response.message);
                        $('#uploadForm')[0].reset();
                        table.ajax.reload();
                    } else {
                        alert('Error: ' + response.message);
                    }
                },
                error: function () {
                    $('#btnUpload').prop('disabled', false);
                    $('#uploadProgress').addClass('d-none');
                    alert('Upload Failed due to server error.');
                }
            });
        });

        // Auto-submit the form when a file is selected
        $('input[name="bulk_file"]').on('change', function () {
            if (this.files && this.files.length > 0) {
                $('#uploadForm').trigger('submit');
            }
        });
    });
</script>