<?php

ini_set('display_errors',1);
ini_set('display_startup_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;

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if(!$id){
die("Invalid quotation.");
}

/* ===============================
FETCH QUOTATION
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM quotations
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$id,$company_id]);
$quote = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$quote){
die("Quotation not found.");
}

/* ===============================
FETCH ITEMS
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM quotation_items
WHERE quotation_id = ?
ORDER BY id ASC
");

$stmt->execute([$id]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
LOAD PRODUCTS + SERVICES
================================ */

$stmt = $pdo->prepare("
SELECT 
id,
sku,
product_name,
description,
selling_price,
item_type
FROM inventory_products
WHERE company_id = ?
AND status = 'active'
ORDER BY product_name
");

$stmt->execute([$company_id]);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

$breadcrumb = "Edit Quotation";
require_once __DIR__ . '/../../../includes/layout.php';

?>

<div class="container">

<div class="page-header">
<h2>Edit Quotation <?= htmlspecialchars($quote['quote_number']) ?></h2>
</div>

<form method="POST" action="update.php?id=<?= $id ?>">

<div class="table-wrap">

<table class="table" id="quoteTable">

<thead>
<tr>
<th>Product / Service</th>
<th>SKU</th>
<th>Description</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
</thead>

<tbody id="quoteBody">

<?php foreach($items as $item): ?>

<tr class="quote-row">

<td>

<select name="product_id[]" class="product-select">

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

<?php foreach($products as $p): ?>

<option
value="<?= $p['id'] ?>"
data-sku="<?= htmlspecialchars($p['sku']) ?>"
data-desc="<?= htmlspecialchars($p['description']) ?>"
data-price="<?= $p['selling_price'] ?>"
data-type="<?= htmlspecialchars($p['item_type'] ?? 'PRODUCT') ?>"
<?= $p['id'] == $item['product_id'] ? 'selected' : '' ?>
>

<?= htmlspecialchars((($p['item_type'] ?? 'PRODUCT') === 'SERVICE' ? '[SERVICE] ' : '') . $p['sku'].' - '.$p['product_name']) ?>

</option>

<?php endforeach; ?>

</select>

</td>

<td class="sku"><?= htmlspecialchars($item['sku']) ?></td>

<td>
<textarea name="description[]" class="description"><?= htmlspecialchars($item['description']) ?></textarea>
</td>

<td>
<input type="number" name="qty[]" class="qty" value="<?= $item['quantity'] ?>">
</td>

<td>
<input type="number" name="price[]" class="price" value="<?= $item['unit_price'] ?>">
</td>

<td class="line-total"><?= number_format($item['total'],2) ?></td>

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

</tr>

<tr class="comment-row">

<td colspan="7">

<label>Item Comment</label>

<textarea name="item_comment[]" class="item-comment"><?= htmlspecialchars($item['item_comment']) ?></textarea>

</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

<br>

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

<br><br>

<div class="quote-settings">

<div class="quote-setting">

<label><strong>Valid Until</strong></label>

<input
type="date"
name="valid_until"
value="<?= htmlspecialchars($quote['valid_until'] ?? '') ?>">

</div>

<div class="quote-setting">

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

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

<option value="0" <?= empty($quote['vat_enabled']) ? 'selected' : '' ?>>
No VAT
</option>

<option value="1" <?= !empty($quote['vat_enabled']) ? 'selected' : '' ?>>
Apply VAT (15%)
</option>

</select>

</div>

</div>

<br><br>

<div class="totals">

<strong>Subtotal:</strong>
R <span id="subtotal"><?= number_format($quote['subtotal'],2) ?></span><br>

<strong>VAT:</strong>
R <span id="vat"><?= number_format($quote['vat_total'],2) ?></span><br>

<strong>Total:</strong>
R <span id="total"><?= number_format($quote['total'],2) ?></span>

</div>

<br>

<button type="submit" class="btn success">
Update Quotation
</button>

</form>

</div>

<script>

/* ===============================
PRODUCT OPTIONS
================================ */

const productOptions = `
<option value="">Select item</option>
<?php foreach($products as $p): ?>
<option
value="<?= $p['id'] ?>"
data-sku="<?= htmlspecialchars($p['sku']) ?>"
data-desc="<?= htmlspecialchars($p['description']) ?>"
data-price="<?= $p['selling_price'] ?>"
data-type="<?= htmlspecialchars($p['item_type'] ?? 'PRODUCT') ?>"
>
<?= htmlspecialchars((($p['item_type'] ?? 'PRODUCT') === 'SERVICE' ? '[SERVICE] ' : '') . $p['sku'].' - '.$p['product_name']) ?>
</option>
<?php endforeach; ?>
`;

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

function calculateRow(row){

let qty = parseFloat(row.querySelector(".qty").value) || 0;
let price = parseFloat(row.querySelector(".price").value) || 0;

let total = qty * price;

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);

}

/* ===============================
PRODUCT AUTO FILL
================================ */

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

if(e.target.classList.contains("product-select")){

let option = e.target.selectedOptions[0];
let row = e.target.closest("tr");

row.querySelector(".sku").innerText = option.dataset.sku || "";
row.querySelector(".description").value = option.dataset.desc || "";
row.querySelector(".price").value = option.dataset.price || "";

let type = option.dataset.type || "PRODUCT";

if(type === "SERVICE"){
row.querySelector(".qty").value = 1;
}

calculateRow(row);

}

});

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

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

if(
e.target.classList.contains("qty") ||
e.target.classList.contains("price")
){
let row = e.target.closest("tr");
calculateRow(row);
}

});

/* ===============================
ADD ITEM
================================ */

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

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

let itemRow = document.createElement("tr");
itemRow.className = "quote-row";

itemRow.innerHTML = `
<td>
<select name="product_id[]" class="product-select">
${productOptions}
</select>
</td>
<td class="sku"></td>
<td>
<textarea name="description[]" class="description"></textarea>
</td>
<td>
<input type="number" name="qty[]" class="qty" value="1">
</td>
<td>
<input type="number" name="price[]" class="price">
</td>
<td class="line-total">0.00</td>
<td>
<button type="button" class="btn btn-danger removeRow">Remove</button>
</td>
`;

let commentRow = document.createElement("tr");
commentRow.className = "comment-row";

commentRow.innerHTML = `
<td colspan="7">
<label>Item Comment</label>
<textarea name="item_comment[]" class="item-comment"></textarea>
</td>
`;

tbody.appendChild(itemRow);
tbody.appendChild(commentRow);

});

/* ===============================
REMOVE ITEM
================================ */

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

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

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

row.remove();

if(commentRow && commentRow.classList.contains("comment-row")){
commentRow.remove();
}

calculateTotals();

}

});

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

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

</script>

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