<?php 
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
    // Process the uploaded file
    $csvFile = $_FILES['file']['tmp_name'];

    // Read the file content
    $fileHandle = fopen($csvFile, 'r');
    $previewData = [];
    while (($data = fgetcsv($fileHandle)) !== FALSE) {
        $previewData[] = $data;
    }
    fclose($fileHandle);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <?php $title = "Receipt Uploads";
    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 -->
    <!-- ============================================================== -->
    <!-- Overlay Div -->
    <div id="overlay" style="display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); z-index: 2; cursor: pointer;">
        <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); color: white;">
            Parsing Statement...
        </div>
    </div>
    
    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="header-title">Receipt File Upload</h4>
                                <p class="sub-header">
                                    Browse to where you have the statement then upload it here.
                                </p>
                                <form id="csvUploadForm" action="upload.php" method="post" enctype="multipart/form-data">
                                    <select class="form-control" id="companySelect" name="company_id" data-toggle="select2" required>
                                        <option value="">Select Company</option>    
                                        <!-- Options will be loaded dynamically -->
                                    </select>
                                    </br>
                                    </br>
                                    </br>
                                    <input type="file" name="file" id="csvFileInput" />
                                    <button type="button" class="btn btn-info rounded-pill waves-effect waves-light" id="previewButton">
                                        Preview Data
                                    </button>
                                    <input class="btn btn-soft-success rounded-pill waves-effect waves-light" type="submit" value="Upload File" name="submit">
                                </form>


                            </div>

                        </div> <!-- end card-->
                    </div><!-- end col -->
                </div>
                <!-- end row -->
                
                <div class="card">
                    <div class="card-body">
                        <h4 class="header-title">Preview Uploaded Data</h4>
                        <div class="table-responsive">
                            <table class="table table-bordered" id="csvPreviewTable">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Category</th>
                                        <th>Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Data rows will be added here dynamically -->
                                </tbody>
                            </table>

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

            </div> <!-- container -->

        </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>