<?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 CATEGORIES
============================== */

$stmt = $pdo->prepare("
SELECT id, category_name
FROM inventory_categories
WHERE company_id = ?
ORDER BY category_name
");

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


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

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

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


/* ===============================
LOAD CUSTOMER COMPANIES
================================ */

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

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


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

$breadcrumb = "Create Quotation";
require_once __DIR__ . '/../../../includes/layout.php';
?>

<div class="container">

<div class="page-header">
<h2>Create Quotation</h2>
<p class="page-subtitle">Create a quotation using products or services from your inventory.</p>

<a href="index.php" class="btn btn-light" style="margin-top:10px;">
← Back to Quotations
</a>

</div>


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


<!-- CUSTOMER -->

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

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

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

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

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

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

<?php endforeach; ?>

</select>

</div>



<!-- CATEGORY FILTER -->

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

<label><strong>Product Category</strong></label><br>

<select id="categoryFilter" style="width:350px">

<option value="">All Categories</option>

<?php foreach($categories as $cat): ?>

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

<?php endforeach; ?>

</select>

</div>



<!-- PRODUCT TABLE -->

<div class="table-wrap">

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

<thead>

<tr>
<th style="width:25%">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">

<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-category="<?= $p['category_id'] ?>"
data-sku="<?= htmlspecialchars($p['sku'] ?? '') ?>"
data-desc="<?= htmlspecialchars($p['description'] ?? '') ?>"
data-price="<?= $p['selling_price'] ?>"
data-type="<?= $p['item_type'] ?>"
>

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

</option>

<?php endforeach; ?>

</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>

</tr>


<tr class="comment-row">

<td colspan="7">

<label>Item Comment</label>

<textarea
name="item_comment[]"
class="item-comment"
placeholder="Add comment under this item"
></textarea>

</td>

</tr>

</tbody>

</table>

</div>



<!-- ADD ITEM -->

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

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

</div>



<!-- QUOTE SETTINGS -->

<div style="display:flex;gap:30px;margin-bottom:20px;flex-wrap:wrap;">

<div>

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

<input type="date" name="valid_until" required>

</div>

<div>

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

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

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

</select>

</div>

</div>



<!-- TOTALS -->

<div class="totals" style="margin-top:25px">

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



<!-- SAVE -->

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

<button type="submit" class="btn btn-primary">
Save Quotation
</button>

</div>

</form>

</div>



<script>

/* ===============================
CATEGORY FILTER
================================ */

document.getElementById("categoryFilter").addEventListener("change", function(){

let category = this.value;

document.querySelectorAll(".product-select option").forEach(function(opt){

if(!opt.dataset.category){
return;
}

if(category === "" || opt.dataset.category === category){
opt.style.display = "block";
}else{
opt.style.display = "none";
}

});

});


/* ===============================
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);

}

});


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

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 applyVAT = document.getElementById("vatToggle").value;

let vat = 0;

if(applyVAT == "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 CHANGES
================================ */

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 ROW
================================ */

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

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

let productRow = tbody.querySelector(".quote-row").cloneNode(true);

let commentRow = tbody.querySelector(".comment-row").cloneNode(true);

productRow.querySelectorAll("input, textarea").forEach(el => el.value="");

productRow.querySelector(".sku").innerText = "";

productRow.querySelector(".line-total").innerText = "0.00";

commentRow.querySelector("textarea").value = "";

tbody.appendChild(productRow);

tbody.appendChild(commentRow);

});


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

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'; ?>