<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();
requirePermission('finance.manage');

require_once __DIR__ . '/../../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

/* ===============================
LOAD CUSTOMERS
================================ */

$stmt = $pdo->prepare("
SELECT id, company_name
FROM companies
WHERE status = 'ACTIVE'
ORDER BY company_name
");

$stmt->execute();

$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
LAYOUT
================================ */

$breadcrumb = "Create Invoice";

require_once __DIR__ . '/../../../includes/layout.php';

?>

<div class="container">

<div class="page-header">
<h2>Create Invoice</h2>
<p class="page-subtitle">Create a manual invoice.</p>
</div>

<form method="POST" action="save.php">

<!-- CUSTOMER -->

<div style="margin-bottom:20px">

<label><strong>Customer</strong></label><br>

<select name="customer_id" required style="width:350px">

<option value="">Select Customer</option>

<?php foreach ($customers as $c): ?>

<option value="<?= $c['id'] ?>">
<?= htmlspecialchars($c['company_name']) ?>
</option>

<?php endforeach; ?>

</select>

</div>


<!-- ITEMS -->

<div class="table-wrap">

<table id="invoiceTable">

<thead>

<tr>
<th>Description</th>
<th>Units</th>
<th>Rate</th>
<th>Total</th>
<th></th>
</tr>

</thead>

<tbody id="invoiceBody">

<tr class="invoice-row">

<td>
<input type="text" name="label[]" style="width:100%">
</td>

<td>
<input type="number" name="units[]" class="units" value="1">
</td>

<td>
<input type="number" name="rate[]" class="rate">
</td>

<td class="line-total">0.00</td>

<td>
<button type="button" class="btn btn-danger removeRow">Remove</button>
</td>

</tr>

</tbody>

</table>

</div>

<br>

<button type="button" id="addRow" class="btn">+ Add Item</button>

<br><br>


<!-- VAT -->

<div>

<label><strong>Apply VAT?</strong></label>

<select id="vatToggle" name="apply_vat">

<option value="0">No VAT</option>
<option value="1">Apply VAT (15%)</option>

</select>

</div>

<br>


<!-- TOTALS -->

<div class="totals">

<strong>Subtotal:</strong>
R <span id="subtotal">0.00</span><br>

<strong>VAT:</strong>
R <span id="vat">0.00</span><br>

<strong>Total:</strong>
R <span id="total">0.00</span>

</div>

<br>

<button type="submit" class="btn success">
Save Invoice
</button>

</form>

</div>



<script>

/* ===============================
CALCULATE ROW
================================ */

function calculateRow(row){

let units = parseFloat(row.querySelector(".units").value) || 0;
let rate = parseFloat(row.querySelector(".rate").value) || 0;

let total = units * rate;

row.querySelector(".line-total").innerText = total.toFixed(2);

calculateTotals();

}


/* ===============================
CALCULATE TOTALS
================================ */

function calculateTotals(){

let subtotal = 0;

document.querySelectorAll(".line-total").forEach(function(el){

subtotal += parseFloat(el.innerText) || 0;

});

let vatEnabled = document.getElementById("vatToggle").value;

let vat = 0;

if(vatEnabled == "1"){
vat = subtotal * 0.15;
}

let total = subtotal + vat;

document.getElementById("subtotal").innerText = subtotal.toFixed(2);
document.getElementById("vat").innerText = vat.toFixed(2);
document.getElementById("total").innerText = total.toFixed(2);

}


/* ===============================
INPUT CHANGE
================================ */

document.addEventListener("input",function(e){

if(
e.target.classList.contains("units") ||
e.target.classList.contains("rate")
){

let row = e.target.closest("tr");

calculateRow(row);

}

});


/* ===============================
ADD ROW
================================ */

document.getElementById("addRow").addEventListener("click",function(){

let tbody = document.getElementById("invoiceBody");

let row = document.createElement("tr");

row.className = "invoice-row";

row.innerHTML = `

<td>
<input type="text" name="label[]" style="width:100%">
</td>

<td>
<input type="number" name="units[]" class="units" value="1">
</td>

<td>
<input type="number" name="rate[]" class="rate">
</td>

<td class="line-total">0.00</td>

<td>
<button type="button" class="btn btn-danger removeRow">Remove</button>
</td>

`;

tbody.appendChild(row);

});


/* ===============================
REMOVE ROW
================================ */

document.addEventListener("click",function(e){

if(e.target.classList.contains("removeRow")){

let row = e.target.closest("tr");

row.remove();

calculateTotals();

}

});


/* ===============================
VAT TOGGLE
================================ */

document.getElementById("vatToggle").addEventListener("change",function(){
calculateTotals();
});

</script>

<?php require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>