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


    <?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 action="upload.php" method="post" class="dropzone" id="myAwesomeDropzone"
                                    data-plugin="dropzone" data-previews-container="#file-previews"
                                    data-upload-preview-template="#uploadPreviewTemplate">
                                    <div class="fallback">
                                        <input name="file" type="file" />
                                    </div>
                            
                                    <div class="dz-message needsclick">
                                        <i class="h1 text-muted dripicons-cloud-upload"></i>
                                        <h3>Drop files here or click to upload.</h3>
                                        <span class="text-muted font-13">(Files allowed are: image files (.jpg, .png.), PDF documents and .csv files)</span>
                                    </div>
                                </form>
                            
                                <!-- Preview -->
                                <!--<div class="dropzone-previews mt-3" id="file-previews"></div>-->
                                
                                <!-- Button -->
                                <!--<button class="btn btn-primary" type="button" id="submit-all">POST</button>-->
                                <form id="csvUploadForm" action="upload.php" method="post" enctype="multipart/form-data">
                                    <input type="file" name="file" id="csvFileInput" />
                                    <button type="button" class="btn btn-info rounded-pill waves-effect waves-light" id="previewButton">
                                        <span class="btn-label"><i class="mdi mdi-alert-circle-outline"></i></span>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>
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);
            initializeDataTable();
        };
    } else {
        alert("Please select a CSV file to preview.");
    }
});

function showOverlay() {
    document.getElementById('overlay').style.display = 'block';
}

function hideOverlay() {
    document.getElementById('overlay').style.display = 'none';
}

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

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

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

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

        tableBody.innerHTML += html;
    });

    initializeDataTable(); // Initialize DataTable here
}

function initializeDataTable() {
    $('#csvPreviewTable').DataTable({
        destroy: true, // Destroy any existing DataTable instance before re-initializing
        // DataTable search and pagination features are enabled by default
    });
}

</script>

</body>

</html>