<?php
session_start();
// Include necessary files and configurations

// Check if company_id is set in the session
if (!isset($_SESSION['company_id'])) {
    // Redirect to login page or handle the error as needed
    die("Access denied. Please log in to access this page.");
}
$companyId = $_SESSION['company_id']; 

// Include database connection file
include('includes/dbconn.php');
function generateInvoiceNumber($conn) {
    $prefix = "FAS-";

    // Lock the counter to ensure atomicity in case of simultaneous requests
    $conn->query("LOCK TABLES counter WRITE, invoices READ");

    // Get the current counter value or initialize if the table is empty
    $result = $conn->query("SELECT counter_value FROM counter");

    // Check for query execution errors
    if (!$result) {
        die("Error fetching counter value: " . $conn->error);
    }

    // Check if there are any rows
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $counter_value = $row['counter_value'];
    } else {
        // No rows returned, initialize with a default value
        $counter_value = 1;

        // Insert a new row with the default value and an empty generated_invoice_number
        $conn->query("INSERT INTO counter (counter_value, generated_invoice_number) VALUES ($counter_value, '')");

        // Note: You may want to handle the case where the insert fails as well
    }

    // Generate a padded invoice number (e.g., FAS-000001)
    $invoice_number = $prefix . str_pad($counter_value, 6, '0', STR_PAD_LEFT);

    // Check if the generated number already exists in the invoices table
    $checkQuery = "SELECT * FROM invoices WHERE invoice_number = '$invoice_number'";
    $result = $conn->query($checkQuery);

    // If the number exists, regenerate
    while ($result->num_rows > 0) {
        $counter_value++;
        $invoice_number = $prefix . str_pad($counter_value, 6, '0', STR_PAD_LEFT);

        // Check again
        $result = $conn->query("SELECT * FROM invoices WHERE invoice_number = '$invoice_number'");
    }

    // Increment the counter value and update the counter table
    $conn->query("UPDATE counter SET counter_value = $counter_value, generated_invoice_number = '$invoice_number'");

    // Unlock the counter
    $conn->query("UNLOCK TABLES");

    return $invoice_number;
}

?>

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

<head>

    <?php
    $title = "List Invoices";
    include 'partials/title-meta.php';
    ?>

    <link href="assets/libs/mohithg-switchery/switchery.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/multiselect/css/multi-select.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/selectize/css/selectize.bootstrap3.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">

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

</head>

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

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

    <?php
    $pagetitle = "List Invoices";
    include 'partials/menu.php';
    ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

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

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

                <div class="card">
                    <div class="card-body">
                        <h4 class="header-title">List Invoices</h4>
                        <p class="sub-header">Client invoices.</p>

                        <div class="table-responsive">
                                    <table id="myTable" class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Client Name</th>
                                                <th>Invoice Number</th>
                                                <th>Total Amount</th>
                                                <th>Due Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                                <?php
                                                include('includes/dbconn.php');
                                            
                                                // Fetch data from the 'clients' table
                                                //$query = "SELECT invoices.*, clients.client_name FROM invoices JOIN clients ON invoices.client_id = clients.client_id";
                                                
                                                // Fetch data from the 'clients' table
                                                $query = "SELECT invoices.*, clients.client_name 
                                                          FROM invoices 
                                                          JOIN clients ON invoices.client_id = clients.client_id 
                                                          WHERE clients.company_id = $companyId";

                                                
                                                $result = mysqli_query($conn, $query);
                                            
                                                // Assuming $user_level is defined and contains the user's level
                                                $user_level = 9; // Example user level for admin
                                            
                                                // Loop through the result set and populate the table
                                                while ($row = mysqli_fetch_assoc($result)) {
                                                    echo "<tr>";
                                                    echo "<td>" . $row['client_name'] . "</td>";
                                                    echo "<td>" . $row['invoice_number'] . "</td>";
                                                    echo "<td>" . $row['total_amount'] . "</td>";
                                                    echo "<td>" . $row['due_date'] . "</td>";
                                            
                                                    // Check if user has sufficient level (assuming you have user authentication)
                                                    if ($user_level >= 9) {
                                                        echo "<td class='text-center'>
                                                                  <ul class='list-inline me-auto mb-0'>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='Edit'>
                                                                          <a href='edit_invoice.php?id=" . $row['invoice_id'] . "' class='avtar avtar-xs btn-link-secondary btn-pc-default'>
                                                                              <i class='ti ti-pencil f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='View'>
                                                                          <a href='invoice_details.php?invoice_id=" . $row['invoice_id'] . "' class='avtar avtar-xs btn-link-secondary btn-pc-default'>
                                                                              <i class='ti ti-eye f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                      <li class='list-inline-item align-bottom' data-bs-toggle='tooltip' title='Delete'>
                                                                          <a href='delete_invoice.php?invoice_id=" . $row['invoice_id'] . "' class='avtar avtar-xs btn-link-danger btn-pc-default'>
                                                                              <i class='ti ti-trash f-18'></i>
                                                                          </a>
                                                                      </li>
                                                                  </ul>
                                                              </td>";
                                                    } else {
                                                        // If user level is not sufficient, display a placeholder or message
                                                        echo "<td class='text-center'>Insufficient Privileges</td>";
                                                    }
                                            
                                                    echo "</tr>";
                                                }
                                            
                                                // Close the result set and connection
                                                mysqli_free_result($result);
                                                mysqli_close($conn);
                                                ?>
                                            </tbody>
                                    </table>
                                </div>

                    </div> <!-- end card-body-->
                </div> <!-- end card-->

            </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';
?>

<!-- Plugin js-->
<script src="assets/libs/parsleyjs/parsley.min.js"></script>

<!-- Validation init js-->
<script src="assets/js/pages/form-validation.init.js"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>
<script src="assets/libs/selectize/js/standalone/selectize.min.js"></script>
<script src="assets/libs/mohithg-switchery/switchery.min.js"></script>
<script src="assets/libs/multiselect/js/jquery.multi-select.js"></script>
<script src="assets/libs/select2/js/select2.min.js"></script>
<script src="assets/libs/jquery-mockjax/jquery.mockjax.min.js"></script>
<script src="assets/libs/devbridge-autocomplete/jquery.autocomplete.min.js"></script>
<script src="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.js"></script>
<script src="assets/libs/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
<script>
    $(document).ready(function() {
        $('#client_name').select2();
    });
</script>
    <!-- DataTables initialization -->
    <script>
    $(document).ready( function () {
        $('#myTable').DataTable({
            // Optional: Add configuration here
        });
    } );
    </script>
<script>
    // Get today's date
    var today = new Date();

    // Format it as YYYY-MM-DD (which is the format commonly used in databases)
    var formattedDate = today.toISOString().substr(0, 10);

    // Set the default value of the input field to today's date
    document.getElementById("start_date").value = formattedDate;
</script>

</body>

</html>
