<?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;
$role_id    = $_SESSION['role_id'] ?? 0;

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

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

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

if($role_id == 7){

$stmt = $pdo->prepare("
SELECT q.*, c.company_name, c.email, c.phone, c.address, c.city, c.province
FROM quotations q
LEFT JOIN companies c ON q.customer_id = c.id
WHERE q.id = ?
");

$stmt->execute([$id]);

}else{

$stmt = $pdo->prepare("
SELECT q.*, c.company_name, c.email, c.phone, c.address, c.city, c.province
FROM quotations q
LEFT JOIN companies c ON q.customer_id = c.id
WHERE q.id = ?
AND q.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);

/* ===============================
STATUS HELPER
================================ */

function quote_status_class($status){

$status = strtolower(trim($status));

switch($status){

case 'converted':
return 'blue';

case 'draft':
return 'gray';

case 'sent':
return 'orange';

case 'approved':
return 'green';

default:
return 'gray';

}

}

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

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

?>

<div class="container">

<!-- COMPANY HEADER -->

<div style="display:flex;align-items:center;margin-bottom:25px">

<img src="/assets/logo.png" style="height:60px;margin-right:20px">

<div>

<strong>EDM Solutions</strong><br>
Smart Metering. Simplified.<br>
info@edmsolutions.co.za<br>
www.edmsolutions.co.za

</div>

</div>


<div class="page-header">

<h2>Quotation <?= htmlspecialchars($quote['quote_number']) ?></h2>

<p class="page-subtitle">
Created on <?= date("d M Y",strtotime($quote['quote_date'])) ?>
</p>

</div>


<!-- QUOTE INFO -->

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

<div>

<strong>Quote Number</strong><br>
<?= htmlspecialchars($quote['quote_number']) ?>

<br><br>

<strong>Quote Date</strong><br>
<?= date("d M Y",strtotime($quote['quote_date'])) ?>

<br><br>

<strong>Valid Until</strong><br>
<?= !empty($quote['valid_until']) ? date("d M Y",strtotime($quote['valid_until'])) : 'Not specified' ?>

</div>

<div>

<strong>Status</strong><br>

<span class="status <?= quote_status_class($quote['status'] ?? '') ?>">
<?= htmlspecialchars($quote['status'] ?? 'Draft') ?>
</span>

<br><br>

<strong>VAT Applied</strong><br>

<?php if(!empty($quote['vat_enabled'])): ?>
Yes (15%)
<?php else: ?>
No VAT
<?php endif; ?>

</div>

</div>


<!-- CUSTOMER -->

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

<h3>Customer</h3>

<?php if(!empty($quote['company_name'])): ?>

<strong><?= htmlspecialchars($quote['company_name']) ?></strong><br>

<?= htmlspecialchars($quote['email'] ?? '') ?><br>

<?= htmlspecialchars($quote['phone'] ?? '') ?><br>

<?= htmlspecialchars($quote['address'] ?? '') ?><br>

<?= htmlspecialchars($quote['city'] ?? '') ?>
<?= htmlspecialchars($quote['province'] ?? '') ?>

<?php else: ?>

<span class="muted">No customer assigned.</span>

<?php endif; ?>

</div>


<!-- ACTIONS -->

<div class="topbar">

<a class="btn" href="index.php">← Back</a>

<a class="btn" href="edit.php?id=<?= (int)$quote['id'] ?>">
Edit
</a>

<button onclick="window.print()" class="btn">
Print
</button>

<a href="preview.php?id=<?= (int)$quote['id'] ?>" class="btn">
Preview
</a>

<a class="btn" href="pdf.php?id=<?= (int)$quote['id'] ?>">
Download PDF
</a>

<?php if(strtoupper($quote['status'] ?? '') !== 'CONVERTED'): ?>

<a class="btn green" href="convert_invoice.php?id=<?= (int)$quote['id'] ?>">
Convert to Invoice
</a>

<?php else: ?>

<span class="btn gray">
Already Converted
</span>

<?php endif; ?>

</div>


<!-- ITEMS -->

<div class="table-wrap">

<table>

<thead>
<tr>
<th>Item</th>
<th>SKU</th>
<th>Description</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>

<tbody>

<?php if(!$items): ?>

<tr>
<td colspan="6">No quotation items found.</td>
</tr>

<?php else: ?>

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

<tr>

<td><?= htmlspecialchars($item['product_name'] ?? '') ?></td>

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

<td><?= nl2br(htmlspecialchars($item['description'] ?? '')) ?></td>

<td><?= (float)($item['quantity'] ?? 0) ?></td>

<td>R <?= number_format((float)($item['unit_price'] ?? 0),2) ?></td>

<td>R <?= number_format((float)($item['total'] ?? 0),2) ?></td>

</tr>

<?php if(!empty($item['item_comment'])): ?>

<tr>
<td colspan="6">
<strong>Comment:</strong>
<?= nl2br(htmlspecialchars($item['item_comment'])) ?>
</td>
</tr>

<?php endif; ?>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>


<!-- TOTALS -->

<div style="display:flex;justify-content:flex-end;margin-top:30px">

<div style="width:300px">

<div style="display:flex;justify-content:space-between">
<span>Subtotal</span>
<span>R <?= number_format((float)($quote['subtotal'] ?? 0),2) ?></span>
</div>

<div style="display:flex;justify-content:space-between">
<span>VAT</span>
<span>
<?php if(!empty($quote['vat_enabled'])): ?>
R <?= number_format((float)($quote['vat_total'] ?? 0),2) ?>
<?php else: ?>
Not Applied
<?php endif; ?>
</span>
</div>

<hr>

<div style="display:flex;justify-content:space-between;font-size:18px;font-weight:bold">
<span>Total</span>
<span>R <?= number_format((float)($quote['total'] ?? 0),2) ?></span>
</div>

</div>

</div>


<!-- NOTES -->

<?php if(!empty($quote['notes'])): ?>

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

<h3>Notes</h3>

<?= nl2br(htmlspecialchars($quote['notes'])) ?>

</div>

<?php endif; ?>


<?php if(!empty($quote['terms'])): ?>

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

<h3>Terms & Conditions</h3>

<?= nl2br(htmlspecialchars($quote['terms'])) ?>

</div>

<?php endif; ?>

</div>

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