<?php
if (!isset($_GET['id'])) {
    header('Location: 404');
    exit;
}

include_once "global.php";

if (isset($_GET["id"])) {
    $invId = $functions->decode($_GET["id"]);
    $sql = "SELECT * FROM invoices WHERE id = ?";
    $invData = $dbF->getRow($sql, [$invId]);
}

if ($dbF->rowCount == 0) {
    header('Location: 404');
    exit;
}

$pageTitle = 'Edit Invoice - ';
include_once 'header.php';

$sqlDocs = "SELECT * FROM `invoice_docs` WHERE `invoice_id` = ?";
$invDocsData = $dbF->getRow($sqlDocs, [$invId]);

$invDocs = '';
if ($dbF->rowCount > 0) {
    $invDocs = json_decode($invDocsData["docs"]);
}

if (!empty($invDocsData["pdf_file"])) {
    $path = WEB_URL . '/images/' . $invDocsData["pdf_file"];
    $pdfLink = "<a href='" . $path . "' target='_blank'>Current PDF</a>";
} else {
    $pdfLink = "";
}

$invoiceDetail = $productClass->getInvoiceDetailsById($invId);
$domain = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_domain');
$rgStartDate = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_rg_date');
$paidDate = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_paid_date');
$paidAmount = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_amount');
$vendorName = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_name');
$vendorEmail = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_email');
$vendorPhone = $productClass->invoiceDetailInfoArray($invoiceDetail, 'vendor_phone');
?>

<div class="card">
    <div class="card-body p-4">
        <h5 class="mb-4">Edit Invoice</h5>
        <form id="invoiceEditForm" class="row g-3" method="post" enctype="multipart/form-data">
            <input type="hidden" name="invId" value="<?php echo $invId; ?>">
            <input type="hidden" name="invtaxamount" id="invtaxamount" value="<?php echo $invData["tax_amount"]; ?>">
            <div class="col-md-6">
                <label for="invclientId" class="form-label">Client Name <span>*</span></label>
                <select id="invclientId" name="invclientId" class="form-select" disabled>
                    <option selected="" value="">Select...</option>
                    <?php
                    $clients = $productClass->AllClientsArray();
                    foreach ($clients as $client) {
                        $clientId = $client["acc_id"];
                        $clientName = $client["acc_name"];
                        $selectedClient = ($invData['client_id'] == $clientId) ? 'selected' : '';
                        echo "<option value='$clientId' $selectedClient>$clientName</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="col-md-6">
                <label for="invcompany" class="form-label">Company Name <span>*</span></label>
                <input type="text" name="invcompany" id="invcompany" class="form-control"
                    value="<?php echo $invData["client_company"]; ?>" readonly>
            </div>
            <?php
            if ($invData["invoice_company"] == "Bizsoft") {
            ?>
                <div class="col-md-6">
                    <label for="invnumber" class="form-label">Invoice #</label>
                    <input type="text" name="invnumber" id="invnumber" class="form-control"
                        value="<?php echo $invData["invoice_number"]; ?>">
                </div>
            <?php
            }
            ?>
            <div class="col-md-4">
                <label for="invdate" class="form-label">Invoice Date <span>*</span></label>
                <input type="date" name="invdate" id="invdate" class="form-control"
                    value="<?php echo $invData["invoice_date"]; ?>" required>
            </div>
            <div class="col-md-4">
                <label for="invduedate" class="form-label">Due Date <span>*</span></label>
                <input type="date" name="invduedate" id="invduedate" class="form-control"
                    value="<?php echo $invData["due_date"]; ?>" required>
            </div>
            <div class="col-md-4">
                <label for="invfor" class="form-label">Invoice For <span>*</span></label>
                <select name="invfor" id="invfor" class="form-select" required>
                    <option selected="" value="">Select...</option>
                    <option value="Domain + Hosting" <?php if ($invData["invoice_for"] == "Domain + Hosting")
                                                            echo 'selected'; ?>>Domain + Hosting</option>
                    <option value="Hosting" <?php if ($invData["invoice_for"] == "Hosting")
                                                echo 'selected'; ?>>Hosting
                    </option>
                    <option value="Domain" <?php if ($invData["invoice_for"] == "Domain")
                                                echo 'selected'; ?>>Domain
                    </option>
                    <option value="Other" <?php if ($invData["invoice_for"] == "Other")
                                                echo 'selected'; ?>>Other</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="invbilledamount" class="form-label">Invoice Billed Amount <span>*</span></label>
                <input type="number" name="invbilledamount" id="invbilledamount" class="form-control"
                    value="<?php echo $invData["billed_amount"]; ?>" required onkeyup="updateTotalAmount(this);">
            </div>
            <div class="col-md-4">
                <label for="invtype" class="form-label">Invoice Type <span>*</span></label>
                <select name="invtype" id="invtype" class="form-select" required>
                    <option value="sales_tax" <?php if ($invData["invoice_type"] == "sales_tax")
                                                    echo 'selected'; ?>>
                        Including Sales Tax (13%)</option>
                    <option value="normal" <?php if ($invData["invoice_type"] == "normal")
                                                echo 'selected'; ?>>Normal
                    </option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="invtotalbillamount" class="form-label">Invoice Total Billed Amount <span>*</span></label>
                <input type="number" name="invtotalbillamount" id="invtotalbillamount" class="form-control"
                    value="<?php echo $invData["total_billed_amount"]; ?>" required>
            </div>
            <div class="col-md-4">
                <label for="invprototalamount" class="form-label">Project Total Amount</label>
                <input type="number" name="invprototalamount" id="invprototalamount" class="form-control"
                    value="<?php echo $invData["total_amount"]; ?>">
            </div>
            <div class="col-md-4">
                <label for="invrcvdamount" class="form-label">Invoice Received Amount</label>
                <input type="number" name="invrcvdamount" id="invrcvdamount" class="form-control"
                    value="<?php echo $invData["received_amount"]; ?>">
            </div>
            <div class="col-md-4">
                <label for="invstatus" class="form-label">Status <span>*</span></label>
                <select class="form-select" name="invstatus" id="invstatus" required>
                    <option selected="" value="">Select...</option>
                    <?php
                    $invoiceStatuses = $productClass->getInvoiceStatuses();
                    foreach ($invoiceStatuses as $invoiceStatus) {
                        $statusId = $invoiceStatus["id"];
                        $name = $invoiceStatus["name"];
                        $selectedStatus = ($invData['status'] == $statusId) ? 'selected' : '';
                        echo "<option value='$statusId' $selectedStatus>$name</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="col-md-6">
                <label for="invpdf" class="form-label">Upload Invoice (PDF) <?php echo $pdfLink; ?></label>
                <input type="file" name="invpdf" id="invpdf" class="form-control">
                <input type="hidden" name="invpdfold" value="<?php echo $invData["pdf_file"]; ?>">
            </div>
            <?php
            if ($invData["status"] == "7" || $invData["status"] == "8") {
                $style = '';
            } else {
                $style = 'style="display: none;"';
            }
            ?>
            <div class="row g-3" id="recurrenceDiv" <?php echo $style; ?>>
                <div class="col-md-4">
                    <label class="form-label d-block">Recurrence</label>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="invrecurrence" id="Yes" value="Yes" checked>
                        <label class="form-check-label" for="Yes">Yes</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="invrecurrence" id="No" value="No">
                        <label class="form-check-label" for="No">No</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <label for="invrecurrenceduration" class="form-label">Recurrence Duration</label>
                    <input type="number" name="invrecurrenceduration" id="invrecurrenceduration" class="form-control"
                        placeholder="Type number of months of recurrence">
                </div>
                <div class="col-md-4">
                    <label for="invexpduration" class="form-label">Expiry Duration</label>
                    <input type="number" name="invexpduration" id="invexpduration" class="form-control"
                        placeholder="Type number of months of expiry">
                </div>
                <div class="col-md-4">
                    <label for="invpaymode" class="form-label">Payment Mode</label>
                    <select name="invpaymode" id="invpaymode" class="form-select">
                        <option selected="" value="">Select...</option>
                        <option value="Cash" <?php if ($invData["payment_mode"] == "Cash")
                                                    echo 'selected'; ?>>Cash
                        </option>
                        <option value="Cheque" <?php if ($invData["payment_mode"] == "Cheque")
                                                    echo 'selected'; ?>>Cheque
                        </option>
                        <option value="Online Transfer" <?php if ($invData["payment_mode"] == "Online Transfer")
                                                            echo 'selected'; ?>>Online Transfer</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="invbankpost" class="form-label">Bank Post</label>
                    <input type="text" name="invbankpost" id="invbankpost" class="form-control"
                        value="<?php echo $invData["bank_post"]; ?>">
                </div>
                <div class="col-md-6">
                    <label for="invdocs" class="form-label">Upload Document(s)</label>
                    <input type="file" name="invdocs[]" id="invdocs" class="form-control" multiple>
                </div>
                <div class="col-md-12">
                    <?php
                    if (is_array($invDocs) && !empty($invDocs)) {
                        echo '<div class="mt-2"><strong>Existing Documents:</strong><ul class="list-group">';
                        foreach ($invDocs as $key => $doc) {
                            $docUrl = WEB_URL . '/images/' . $doc;
                            echo '<input type="hidden" name="invdocs[]" value="' . $doc . '">';
                            echo "<li class='list-group-item d-flex justify-content-between align-items-center'>
                                        <a href='{$docUrl}' target='_blank'>Document " . ($key + 1) . "</a>
                                        <button type='button' class='btn btn-sm btn-danger removeDocBtn' data-filename='{$doc}' data-inv-id='{$invId}'>Remove</button>
                                    </li>";
                        }
                        echo '</ul></div>';
                    }
                    ?>
                </div>
            </div>
            <div class="col-md-12">
                <label for="invdesc" class="form-label">Description</label>
                <textarea class="form-control" id="invdesc" name="invdesc"
                    rows="3"><?php echo $invData["description"]; ?></textarea>
            </div>
            <div class="showHideDiv" style="display: none;">
                <h5 class="mb-4">Vendor Details</h5>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="vendordomain" class="form-label">Domain</label>
                        <input type="text" name="vendordomain" id="vendordomain" class="form-control"
                            value="<?php echo $domain; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendorrgdate" class="form-label">Registration Start Date</label>
                        <input type="date" name="vendorrgdate" id="vendorrgdate" class="form-control"
                            value="<?php echo $rgStartDate; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="invexpirydate" class="form-label">Exact Expiry Date</label>
                        <input type="date" name="invexpirydate" id="invexpirydate" class="form-control"
                            value="<?php echo $invData["expiry_date"]; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendorpaiddate" class="form-label">Payment Paid Date</label>
                        <input type="date" name="vendorpaiddate" id="vendorpaiddate" class="form-control"
                            value="<?php echo $paidDate; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendoramount" class="form-label">Paid Amount</label>
                        <input type="number" name="vendoramount" id="vendoramount" class="form-control"
                            value="<?php echo $paidAmount; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendorname" class="form-label">Name</label>
                        <input type="text" name="vendorname" id="vendorname" class="form-control"
                            value="<?php echo $vendorName; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendoremail" class="form-label">Email</label>
                        <input type="email" name="vendoremail" id="vendoremail" class="form-control"
                            value="<?php echo $vendorEmail; ?>">
                    </div>
                    <div class="col-md-6">
                        <label for="vendorphone" class="form-label">Phone</label>
                        <input type="tel" name="vendorphone" id="vendorphone" class="form-control"
                            value="<?php echo $vendorPhone; ?>">
                    </div>
                </div>
            </div>
            <div class="col-md-12">
                <div class="d-md-flex d-grid align-items-center gap-3">
                    <button type="submit" class="btn btn-grd-primary px-4">Update</button>
                    <button type="button" onclick="toggleVendorDetails(this)" class="btn btn-grd-royal px-4">Show Other
                        Fields</button>
                </div>
            </div>
        </form>
    </div>
</div>

<?php
include_once 'footer.php';
?>