<?php
session_start();

// Check if CSV data is available in the session
if (!isset($_SESSION['csv_data']) || empty($_SESSION['csv_data'])) {
    echo "No CSV data available to edit.";
    exit;
}

$csvData = $_SESSION['csv_data'];
?>

<!DOCTYPE html>
<html lang="en">
<head>

    <?php $title = "Receipt Uploads - Edit";
    include 'partials/title-meta.php'; ?>

    <!-- Plugins css -->
    <link href="assets/libs/dropzone/min/dropzone.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/dropify/css/dropify.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />


    <?php include 'partials/head-css.php'; ?>

</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Receipt Uploads";
    include 'partials/menu.php'; ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->
    
    <div class="content-page">
        <div class="content">
            
            <div class="card">
                    <div class="card-body">
                        <h4 class="header-title">Preview Uploaded Data</h4>
                        <div class="table-responsive">
                        <form action="process_csv.php" method="post">    
                            <table class="table table-bordered" id="csvPreviewTable">
                                <thead>
                                    <tr>
                                        <th>Account number</th>
                                        <th>Date</th>
                                        <th>Description</th>
                                        <th>Category</th>
                                        <th>Note</th>
                                        <th>Amount</th>
                                        <th>Balance</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($csvData as $rowIndex => $row): ?>
                                        <tr>
                                            <?php foreach ($row as $colIndex => $col): ?>
                                                <td>
                                                    <input type="text" name="data[<?php echo $rowIndex; ?>][<?php echo $colIndex; ?>]" value="<?php echo htmlspecialchars($col); ?>">
                                                </td>
                                            <?php endforeach; ?>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <input class="btn btn-soft-success rounded-pill waves-effect waves-light" type="submit" value="Submit Edited Data" name="submit">
                        </form>
                        </div>
                    </div>
                </div>

        </div> <!-- content -->

        <?php include 'partials/footer.php'; ?>

    </div>

    <!-- ============================================================== -->
    <!-- End Page content -->
    <!-- ============================================================== -->


</div>
<!-- END wrapper -->    
    
<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- Plugins js -->
<script src="assets/libs/dropzone/min/dropzone.min.js"></script>
<script src="assets/libs/dropify/js/dropify.min.js"></script>

<!-- Init js-->
<script src="assets/js/pages/form-fileuploads.init.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>
<script src="assets/libs/select2/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
        $('#companySelect').select2();
    });
</script>
<!-- started adding code from here -->

<script>
$(document).ready(function() {
    // Initialize Select2
    $('#companySelect').select2({
        placeholder: "Select a company",
        allowClear: true,
        ajax: {
            url: 'get_companies.php', // the endpoint to your PHP script
            dataType: 'json',
            processResults: function (data) {
                // Transforms the top-level key of the response object from 'items' to 'results'
                return {
                    results: data.items
                };
            }
        }
    });
});
</script>

<!-- added the code to here -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('previewButton').addEventListener('click', function() {
        var fileInput = document.getElementById('csvFileInput');
        var file = fileInput.files[0];

        if (file) {
            var reader = new FileReader();
            reader.readAsText(file);

            reader.onload = function(event) {
                var csvData = event.target.result;
                var parsedData = parseCSV(csvData);
                displayCSVData(parsedData);
            };
        } else {
            alert("Please select a CSV file to preview.");
        }
    });

    function parseCSV(data) {
        var lines = data.split('\n');
        return lines.map(line => {
            return line.split(',');
        });
    }

    function displayCSVData(data) {
        var tableBody = document.getElementById('csvPreviewTable').querySelector('tbody');
        tableBody.innerHTML = ''; // Clear existing data

        data.forEach(function(row, index) {
            // Skip header row and empty lines
            if (index === 0 || row.length < 3) return;

            var html = "<tr>";
            html += "<td>" + row[0] + "</td>"; // Adjust these indices based on your CSV format
            html += "<td>" + row[1] + "</td>";
            html += "<td>" + row[2] + "</td>";
            html += "</tr>";

            tableBody.innerHTML += html;
        });

        // Now that all rows are added, initialize DataTable
        initializeDataTable();
    }

    function initializeDataTable() {
        // If DataTable is already initialized, destroy it before re-initializing
        if ($.fn.DataTable.isDataTable('#csvPreviewTable')) {
            $('#csvPreviewTable').DataTable().clear().destroy();
        }

        $('#csvPreviewTable
        
        ').DataTable({
        // DataTable options here
        // Enable the search functionality
        searching: true,
        retrieve: true
        });
        }
        });
</script>    
</body>
</html>
