<?php $this->extend("layouts/main"); $this->section("content"); $title = "New Invoice";
$sym = ["GBP"=>"£","EUR"=>"€","USD"=>"$"][$currency] ?? "£";
$prefillItems = $prefill["items"] ?? [["description"=>"","qty"=>1,"unit_price"=>"","discount"=>0,"tax_rate"=>20,"line_total"=>0]];
?>
<script>
window.currencySymbol = "<?php echo $sym ?>";
window.fieldlyTaxRates = <?php echo json_encode(array_map(fn($t)=>["rate"=>$t["rate"],"name"=>$t["name"]],$taxRates)) ?>;
</script>
<div class="row justify-content-center"><div class="col-lg-10">
<div class="mb-3"><a href="/fieldly/public/index.php/invoices" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Back</a></div>
<form method="POST" action="/fieldly/public/index.php/invoices/create">
<?php echo csrf_field() ?>
<input type="hidden" name="quote_id" value="<?php echo $prefill["quote_id"]??"" ?>"/>
<input type="hidden" name="job_id" value="<?php echo $prefill["job_id"]??"" ?>"/>

<div class="card mb-3"><div class="card-header"><h6 class="mb-0">Invoice Details</h6></div><div class="card-body">
<div class="row g-3">
    <div class="col-md-6">
        <label class="form-label">Customer *</label>
        <?php $prefillCustomer = $prefill["customer_id"] ?? null; ?>
        <?php if ($prefillCustomer): $c=db_connect()->table("customers")->where("id",$prefillCustomer)->get()->getRowArray(); ?>
        <input type="text" class="form-control" value="<?php echo esc($c["company_name"]?:$c["first_name"]." ".$c["last_name"]) ?>" readonly/>
        <input type="hidden" name="customer_id" value="<?php echo $prefillCustomer ?>"/>
        <?php else: ?>
        <input type="text" id="customer-search" class="form-control" placeholder="Search customer..."/>
        <input type="hidden" name="customer_id" id="customer_id" required/>
        <div id="customer-results" class="border rounded bg-white shadow-sm" style="display:none;position:absolute;z-index:999;width:400px"></div>
        <?php endif; ?>
    </div>
    <div class="col-md-6"><label class="form-label">Invoice Number</label><input type="text" class="form-control" value="<?php echo esc($nextNum) ?>" readonly/></div>
    <div class="col-md-8"><label class="form-label">Title</label><input type="text" name="title" class="form-control" value="<?php echo esc($prefill["title"]??"") ?>"/></div>
    <div class="col-md-4"><label class="form-label">Due Date</label><input type="date" name="due_date" class="form-control" value="<?php echo date("Y-m-d",strtotime("+30 days")) ?>"/></div>
    <div class="col-12"><label class="form-label">Payment Terms</label><textarea name="payment_terms" class="form-control" rows="1"><?php echo esc($settings["invoice_defaults"]["payment_terms"]??"Payment due within 30 days of invoice date") ?></textarea></div>
</div>
</div></div>

<!-- Line Items -->
<div class="card mb-3"><div class="card-header d-flex justify-content-between align-items-center"><h6 class="mb-0">Line Items</h6></div>
<div class="card-body p-0">
<table class="table mb-0 line-items-table">
<thead><tr><th style="width:40%">Description</th><th>Qty</th><th>Unit Price</th><th>Discount</th><th>Tax Rate</th><th>Total</th><th></th></tr></thead>
<tbody id="line-items-container">
<?php foreach ($prefillItems as $i=>$item): ?>
<tr class="line-item-row">
    <td><input type="text" class="form-control form-control-sm item-desc" name="items[<?php echo $i ?>][description]" value="<?php echo esc($item["description"]??"") ?>" placeholder="Description" required/></td>
    <td style="width:70px"><input type="number" class="form-control form-control-sm item-qty" name="items[<?php echo $i ?>][qty]" value="<?php echo $item["qty"]??1 ?>" min="0" step="0.5"/></td>
    <td style="width:120px"><div class="input-group input-group-sm"><span class="input-group-text"><?php echo $sym ?></span><input type="number" class="form-control item-price" name="items[<?php echo $i ?>][unit_price]" value="<?php echo $item["unit_price"]??"" ?>" min="0" step="0.01" placeholder="0.00"/></div></td>
    <td style="width:80px"><div class="input-group input-group-sm"><input type="number" class="form-control item-discount" name="items[<?php echo $i ?>][discount]" value="<?php echo $item["discount"]??0 ?>" min="0" max="100"/><span class="input-group-text">%</span></div></td>
    <td style="width:130px"><select class="form-select form-select-sm item-tax" name="items[<?php echo $i ?>][tax_rate]"><?php foreach ($taxRates as $tr): ?><option value="<?php echo $tr["rate"] ?>" <?php echo (float)($item["tax_rate"]??20)===(float)$tr["rate"]?"selected":"" ?>><?php echo esc($tr["name"]) ?> (<?php echo $tr["rate"] ?>%)</option><?php endforeach; ?></select></td>
    <td style="width:100px" class="text-end fw-bold item-total"><?php echo $sym.number_format((float)($item["line_total"]??0),2) ?></td>
    <td style="width:40px"><button type="button" class="btn btn-sm btn-outline-danger remove-line-item"><i class="bi bi-trash3"></i></button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="p-3 border-top"><button type="button" class="btn btn-sm btn-outline-secondary" id="add-line-item"><i class="bi bi-plus me-1"></i> Add Line</button></div>
<div class="line-items-total">
    <input type="hidden" name="subtotal" id="subtotal-hidden"/>
    <input type="hidden" name="tax_total" id="tax-hidden"/>
    <input type="hidden" name="total" id="total-hidden"/>
    <div class="d-flex justify-content-end gap-5">
        <div class="text-end"><div class="text-muted small">Subtotal</div><div class="fw-bold" id="subtotal-display"><?php echo $sym ?>0.00</div></div>
        <div class="text-end"><div class="text-muted small">Tax</div><div class="fw-bold" id="tax-display"><?php echo $sym ?>0.00</div></div>
        <div class="text-end"><div class="text-muted small">Total</div><div class="fw-bold fs-5" id="total-display"><?php echo $sym ?>0.00</div></div>
    </div>
</div>
</div></div>

<?php if (!empty($prefill["credits"])): ?>
<div class="card mb-3 border-success"><div class="card-header bg-success bg-opacity-10"><h6 class="mb-0 text-success"><i class="bi bi-coin me-2"></i>Pre-payments Available</h6></div><div class="card-body">
<p class="mb-2" style="font-size:14px">There are pre-payments of <strong><?php echo $sym.number_format($prefill["credit_total"],2) ?></strong> recorded against this job.</p>
<div class="form-check"><input type="checkbox" name="apply_credits" class="form-check-input" id="apply_credits" checked/><label class="form-check-label" for="apply_credits">Apply these pre-payments to this invoice</label></div>
</div></div>
<?php endif; ?>

<div class="card mb-4"><div class="card-header"><h6 class="mb-0">Notes</h6></div><div class="card-body"><textarea name="notes" class="form-control" rows="3" placeholder="Notes visible on invoice..."><?php echo esc($settings["invoice_defaults"]["footer_text"]??"") ?></textarea></div></div>

<div class="d-flex gap-2">
    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i> Create Invoice</button>
    <a href="/fieldly/public/index.php/invoices" class="btn btn-outline-secondary">Cancel</a>
</div>
</form>
</div></div>
<?php $this->endSection(); ?>