<?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 = "Create Client Invoice";
    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" />

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

</head>

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

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

    <?php
    $pagetitle = "Create Client Invoice";
    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">Create Client Invoice</h4>
                        <p class="sub-header">Capture client invoice.</p>

                        <form class="needs-validation" novalidate action="save_invoice.php" method="post">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="mb-3">
                                        <label for="client_name" class="form-label">Client Name</label>
                                        <select class="form-control" id="client_name" name="client_id" data-toggle="select2" required>
                                            <option value="">Select Client</option>
                                            <?php
                                            // Fetch clients from the 'clients' table
                                            $result = mysqli_query($conn, "SELECT client_id, client_name FROM clients");

                                            // Check if there are any rows
                                            if ($result && mysqli_num_rows($result) > 0) {
                                                // Output options for each client
                                                while ($row = mysqli_fetch_assoc($result)) {
                                                    echo "<option value='{$row['client_id']}'>{$row['client_name']}</option>";
                                                }
                                            } else {
                                                echo "<option value=''>No clients found</option>";
                                            }

                                            // Close the result set and connection
                                            mysqli_free_result($result);
                                            ?>
                                        </select>
                                    </div>
                                    <div class="mb-3">
                                        <label for="invoice_number" class="form-label">Invoice Number</label>
                                        <?php
                                        // Assuming $conn is your database connection object
                                        $invoice_number = generateInvoiceNumber($conn);
                                        ?>
                                        <input type="text" class="form-control" id="invoice_number" name="invoice_number" placeholder="Invoice Number" value="<?php echo $invoice_number; ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="discount" class="form-label">Discount</label>
                                        <input type="number" class="form-control" id="discount" name="discount" placeholder="Discount" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="tax" class="form-label">Tax</label>
                                        <input type="number" class="form-control" id="tax" name="tax" placeholder="Tax" required>
                                    </div>
                                </div>

                                <div class="col-lg-6">

                                    
                                    <div class="mb-3">
                                        <label for="due_date" class="form-label">Due Date</label>
                                        <input type="date" class="form-control" id="due_date" name="due_date" required>
                                    </div>

                                    <!-- Invoice Line Items -->
                                    <div class="mb-3">
                                        <label for="description" class="form-label">Description</label>
                                        <input type="text" class="form-control" id="description" name="description[]" placeholder="Description" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="quantity" class="form-label">Quantity</label>
                                        <input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required oninput="calculateTotal()">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="unit_price" class="form-label">Unit Price</label>
                                        <input type="number" class="form-control" id="unit_price" name="unit_price" placeholder="Unit Price" required oninput="calculateTotal()">
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="total_amount" class="form-label">Total Amount</label>
                                        <input type="text" class="form-control" id="total_amount" name="total_amount" placeholder="Total Amount" readonly>
                                    </div>


                                </div>
                            </div>

                            <button class="btn btn-primary" type="submit">Submit form</button>
                        </form>

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

<!-- 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>
<script>
function calculateTotal() {
    var quantity = document.getElementById('quantity').value;
    var unitPrice = document.getElementById('unit_price').value;
    var total = quantity * unitPrice;
    
    document.getElementById('total_amount').value = total.toFixed(2); // Set total amount with two decimal places
}
</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>
