<?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 'includes/dbconn.php';

$invoiceId = isset($_GET['id']) ? intval($_GET['id']) : null;

if (!$invoiceId) {
    header('Location: list_invoices.php');
    exit();
}

// Fetch the invoice data if the page is first loaded
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $invoiceQuery = "SELECT invoices.*, clients.client_name FROM invoices LEFT JOIN clients ON invoices.client_id = clients.client_id WHERE invoices.invoice_id = ?";
    $stmt = $conn->prepare($invoiceQuery);
    $stmt->bind_param('i', $invoiceId);
    $stmt->execute();
    $result = $stmt->get_result();
    $invoice = $result->fetch_assoc();

    // Check if the invoice exists
    if (!$invoice) {
        echo 'Invoice not found.';
        exit();
    }
}

    $total_amount = $total_amount - $discount;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve the updated invoice details
    $client_id = $_POST['client_id'] ?? null;
    $discount = $_POST['discount'] ?? 0.0;
    $tax = $_POST['tax'] ?? 0.0;
    $total_amount = $_POST['total_amount'] ?? 0.0;
    $due_date = $_POST['due_date'] ?? null;

    // Assuming the due_date is already in 'Y-m-d' format
    $updateInvoiceQuery = "UPDATE invoices SET client_id = ?, discount = ?, tax = ?, total_amount = ?, due_date = ? WHERE invoice_id = ?";
    $updateStmt = $conn->prepare($updateInvoiceQuery);
    $updateStmt->bind_param('iddssi', $client_id, $discount, $tax, $total_amount, $due_date, $invoiceId);

    if (!$updateStmt->execute()) {
        echo "Error updating invoice record: " . $conn->error;
        exit();
    }

    // Fetch all line items for the invoice
    $lineItemsQuery = "SELECT line_item_id, quantity, unit_price FROM invoice_line_items WHERE invoice_id = ?";
    $lineItemsStmt = $conn->prepare($lineItemsQuery);
    $lineItemsStmt->bind_param('i', $invoiceId);
    $lineItemsStmt->execute();
    $result = $lineItemsStmt->get_result();

    $totalBeforeDiscountAndTax = 0;
    $lineItems = [];

    while ($row = $result->fetch_assoc()) {
        $lineItemTotal = $row['quantity'] * $row['unit_price'];
        $totalBeforeDiscountAndTax += $lineItemTotal;
        $lineItems[] = array_merge($row, ['total' => $lineItemTotal]);
    }

    // Update each line item with proportionally distributed discount and tax
    foreach ($lineItems as $item) {
        $proportion = $item['total'] / $totalBeforeDiscountAndTax;

        $itemDiscount = $discount * $proportion;
        $itemTax = $tax * $proportion;

        $updateLineItemQuery = "UPDATE invoice_line_items SET discount = ?, tax = ?, total_amount = ? WHERE line_item_id = ?";
        $updateLineItemStmt = $conn->prepare($updateLineItemQuery);

        $newTotalAmount = ($item['quantity'] * $item['unit_price']) - $itemDiscount + $itemTax;

        $updateLineItemStmt->bind_param('dddi', $itemDiscount, $itemTax, $newTotalAmount, $item['line_item_id']);
        $updateLineItemStmt->execute();
    }

    header('Location: invoice_details.php?invoice_id=' . $invoiceId);
    exit();
}

$conn->close();
?>

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

<head>

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

                        <form action="edit_invoice.php?id=<?php echo htmlspecialchars($invoiceId); ?>" method="post">
                            <label for="client_name">Client Name:</label>
                            <input type="text" class="form-control" id="client_name" name="client_name" value="<?php echo htmlspecialchars($invoice['client_name']); ?>" readonly><br>
                            
                            <!-- Hidden field to hold the client ID -->
                            <input type="hidden" name="client_id" value="<?php echo htmlspecialchars($invoice['client_id']); ?>">

                            <label for="total_amount">Discount:</label>
                            <input type="number" class="form-control" step="0.01" id="discount" name="discount" value="<?php echo htmlspecialchars($invoice['discount']); ?>" required><br>
                            
                            <label for="total_amount">Tax:</label>
                            <input type="number" class="form-control" step="0.01" id="tax" name="tax" value="<?php echo htmlspecialchars($invoice['tax']); ?>" required><br>
                            
                            <label for="total_amount">Total Amount:</label>
                            <input type="number" class="form-control" step="0.01" id="total_amount" name="total_amount" value="<?php echo htmlspecialchars($invoice['total_amount']); ?>" required><br>
                    
                            <label for="due_date">Due Date:</label>
                            <input type="date" class="form-control" id="due_date" name="due_date" value="<?php echo htmlspecialchars($invoice['due_date']); ?>" required><br>

                            <!-- Add more fields as necessary -->
                    
                            <button class="btn btn-primary" type="submit">Update Invoice</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>
    // 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>
