<?php
ob_start();

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

include 'auth.php';
include "db.php";

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

if (!$quote_id) {
    die("Invalid Quotation ID");
}

/* 📊 1. FETCH MAIN QUOTATION & CUSTOMER DATA */
$query = "
    SELECT 
        q.id as quote_no,
        q.date,
        q.valid_until,
        q.payment_terms,
        q.custom_terms,
        q.summary_data,
        q.amount as grand_total,
        c.name as customer_name
    FROM quotations q
    LEFT JOIN customers c ON q.customer_id = c.id
    WHERE q.id = ?
";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $quote_id);
$stmt->execute();
$result = $stmt->get_result();
$quotation = $result->fetch_assoc();
$stmt->close();

if (!$quotation) {
    die("Quotation / Estimate Not Found!");
}

// Decode calculations breakdown (Subtotal, Tax, Discount)
$summary = json_decode($quotation['summary_data'], true);

$sub_total = $summary['sub_total'] ?? $quotation['grand_total'];
$tax = $summary['tax'] ?? 0;
$discount = $summary['discount'] ?? 0;
$other = $summary['other'] ?? 0;
$round_off = $summary['round_off'] ?? 0;

// Decode manually typed custom terms array
$custom_terms_list = json_decode($quotation['custom_terms'], true) ?? [];

/* 📦 2. FETCH ITEM DETAILS FROM `quotation_items` TABLE */
$items_query = "
    SELECT 
        q.price,
        q.quantity,
        q.total,
        p.product_name
    FROM quotation_items q
    LEFT JOIN products p ON q.product_id = p.product_id
    WHERE q.quotation_id = ?
";

$stmt_items = $conn->prepare($items_query);
$stmt_items->bind_param("i", $quote_id);
$stmt_items->execute();
$items_result = $stmt_items->get_result();
$products_list = [];
while ($item_row = $items_result->fetch_assoc()) {
    $products_list[] = $item_row;
}
$stmt_items->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Quotation #<?= $quotation['quote_no'] ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

<style>
:root {
    --primary-color: #007bff; /* Professional Blue Accent for Quotes */
    --dark-color: #0C1F3A;
    --light-bg: #f8f9fa;
    --border-color: #e5e7eb;
}

body {
    background: #eef2f7;
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 10px;
    color: #4b5563;
}
.invoice-wrapper {
    max-width: 850px;
    margin: 10px auto;
}
.invoice-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.04);
    padding: 25px 35px;
    position: relative;
    overflow: hidden;
}
.invoice-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(90deg, var(--primary-color), #00c6ff);
}

/* HEADER STYLE */
.invoice-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 2px solid var(--light-bg);
    padding-bottom: 15px;
    margin-bottom: 15px;
}
.company-details h1 {
    margin: 0;
    font-size: 24px;
    color: var(--dark-color);
    font-weight: 700;
}
.company-details p {
    margin: 2px 0;
    font-size: 12px;
    color: #6b7280;
}
.invoice-status-box {
    text-align: right;
}
.invoice-status-box h2 {
    margin: 0;
    font-size: 22px;
    color: var(--primary-color);
    font-weight: 700;
}
.badge-quote {
    background-color: rgba(0, 123, 255, 0.1);
    color: var(--primary-color);
    padding: 3px 10px;
    border-radius: 30px;
    font-size: 11px;
    font-weight: 600;
    display: inline-block;
    margin-top: 3px;
}

/* DETAILS GRID */
.invoice-details-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    margin-bottom: 15px;
}
.info-block h4 {
    margin: 0 0 4px 0;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #9ca3af;
}
.info-block p {
    margin: 1px 0;
    font-size: 13px;
}
.info-block .client-name {
    font-size: 15px;
    font-weight: 600;
    color: var(--dark-color);
}

/* COMPACT TABLE */
table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 15px;
}
thead tr {
    background-color: var(--light-bg);
    border-top: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
}
th {
    padding: 10px;
    font-size: 12px;
    font-weight: 600;
    color: var(--dark-color);
    text-align: left;
}
td {
    padding: 10px;
    border-bottom: 1px solid #f3f4f6;
    font-size: 13px;
    color: #4b5563;
}
.text-right {
    text-align: right;
}

/* SUMMARY CALCULATION */
.invoice-summary {
    display: flex;
    justify-content: flex-end;
    margin-top: 5px;
}
.summary-table {
    width: 280px;
    margin-bottom: 0;
}
.summary-table tr td {
    padding: 4px 0;
    border-bottom: none;
    font-size: 13px;
}
.summary-table tr.total-row td {
    border-top: 2px solid var(--border-color);
    font-size: 16px;
    font-weight: 700;
    color: var(--dark-color);
    padding-top: 8px;
}

/* NARRATION CONTAINER FULL WIDTH */
.narration-container {
    margin-top: 15px;
    padding-top: 10px;
    border-top: 1px dashed var(--border-color);
}
.narration-container h5 {
    margin: 0 0 4px 0;
    font-size: 12px;
    color: var(--dark-color);
    font-weight: 600;
}
.narration-textarea {
    width: 100%;
    height: 45px;
    padding: 6px 10px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-family: inherit;
    font-size: 12px;
    color: #333;
    resize: none;
    background: #fafafa;
}

.invoice-footer {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    border-top: 1px solid var(--light-bg);
    padding-top: 15px;
}
.terms {
    max-width: 60%;
}
.terms h5 {
    margin: 0 0 4px 0;
    font-size: 12px;
    color: var(--dark-color);
}
.terms p {
    margin: 0;
    font-size: 11px;
    color: #555;
    line-height: 1.5;
}
.signature-block {
    text-align: center;
    width: 150px;
}
.signature-line {
    border-bottom: 1px solid #9ca3af;
    margin-bottom: 4px;
    height: 30px;
}
.signature-block p {
    margin: 0;
    font-size: 11px;
}

/* BUTTONS ACTIONS */
.actions {
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
    gap: 10px;
}
.right-actions {
    display: flex;
    gap: 10px;
}
.btn {
    padding: 8px 16px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 12px;
    cursor: pointer;
    border: none;
    transition: 0.3s;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.btn-print {
    background: var(--dark-color);
    color: #fff;
}
.btn-back {
    background: #e5e7eb;
    color: #374151;
}

/* PRINT PREVIEW RULES */
@media print {
    body { background: #fff; padding: 0; }
    .invoice-card { box-shadow: none; padding: 0; margin: 0; }
    .actions { display: none !important; }
    .narration-textarea {
        border: none !important;
        background: transparent !important;
        padding: 0 !important;
        height: auto !important;
    }
}
</style>
</head>
<body>

<div class="invoice-wrapper">
<div class="invoice-card">

    <div class="invoice-header">
        <div class="company-details">
            <h1>TAMEER AL MADINA</h1>
            <p>📍 BARKA INDUSTRIAL AREA</p>
            <p>📞 +968 97300223 | ✉️ tameeralmadinatrading@gmail.com</p>
        </div>
        <div class="invoice-status-box">
            <h2>PRICE ESTIMATE</h2>
            <p style="margin:0; font-size:13px; color:#6b7280;"># QT-00<?= $quotation['quote_no'] ?></p>
            <span class="badge-quote">Quotation Document</span>
        </div>
    </div>

    <div class="invoice-details-grid">
        <div class="info-block">
            <h4>Estimated For (Customer):</h4>
            <p class="client-name"><?= htmlspecialchars($quotation['customer_name']) ?></p>
        </div>
        <div class="info-block" style="text-align: right;">
            <h4>Quotation Details:</h4>
            <p><strong>Date Issued:</strong> <?= date('d M Y', strtotime($quotation['date'])) ?></p>
            <p><strong>Valid Until:</strong> <span style="color:#dc3545; font-weight:600;"><?= date('d M Y', strtotime($quotation['valid_until'])) ?></span></p>
            <p><strong>Payment Option:</strong> <?= htmlspecialchars($quotation['payment_terms']) ?></p>
        </div>
    </div>

    <table>
        <thead>
            <tr>
                <th style="width: 8%;">Sr.</th>
                <th style="width: 47%;">Product Name</th>
                <th style="width: 15%; text-align: right;">Price</th>
                <th style="width: 10%; text-align: right;">Qty</th>
                <th style="width: 20%; text-align: right;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $sr = 1;
            foreach($products_list as $item) {
                echo "<tr>
                    <td>{$sr}</td>
                    <td><strong>" . htmlspecialchars($item['product_name'] ?? 'Item Details') . "</strong></td>
                    <td class='text-right'>" . number_format($item['price'], 2) . "</td>
                    <td class='text-right'>{$item['quantity']}</td>
                    <td class='text-right'>" . number_format($item['total'], 2) . " PKR</td>
                </tr>";
                $sr++;
            }
            ?>
        </tbody>
    </table>

    <div class="invoice-summary">
        <table class="summary-table">
            <tr>
                <td>Sub Total:</td>
                <td class="text-right"><?= number_format($sub_total, 2) ?> PKR</td>
            </tr>
            <?php if($tax > 0): ?>
            <tr>
                <td>(+) Tax:</td>
                <td class="text-right" style="color: #d9534f;"><?= number_format($tax, 2) ?> PKR</td>
            </tr>
            <?php endif; ?>
            <?php if($discount > 0): ?>
            <tr>
                <td>(-) Discount:</td>
                <td class="text-right" style="color: #28a745;"><?= number_format($discount, 2) ?> PKR</td>
            </tr>
            <?php endif; ?>
            <?php if($other > 0): ?>
            <tr>
                <td>(+) Other Charges:</td>
                <td class="text-right"><?= number_format($other, 2) ?> PKR</td>
            </tr>
            <?php endif; ?>
            <?php if($round_off != 0): ?>
            <tr>
                <td>(+/-) Round Off:</td>
                <td class="text-right"><?= number_format($round_off, 2) ?> PKR</td>
            </tr>
            <?php endif; ?>
            <tr class="total-row">
                <td>Grand Total:</td>
                <td class="text-right"><?= number_format($quotation['grand_total'], 2) ?> PKR</td>
            </tr>
        </table>
    </div>

    <div class="narration-container">
        <h5>Internal Notes / Reference Remarks:</h5>
        <textarea class="narration-textarea" placeholder="Type dynamic comments here..."></textarea>
    </div>

    <div class="invoice-footer">
        <div class="terms">
            <h5>Terms & Conditions</h5>
            <?php 
            if(count($custom_terms_list) > 0) {
                $tc_num = 1;
                foreach($custom_terms_list as $term) {
                    echo "<p>{$tc_num}. " . htmlspecialchars($term) . "</p>";
                    $tc_num++;
                }
            } else {
                echo "<p>1. Prices are valid only till the quotation validity date.</p>";
                echo "<p>2. Standard corporate performa statement rules apply.</p>";
            }
            ?>
        </div>
        <div class="signature-block">
            <div class="signature-line"></div>
            <p>Prepared By</p>
        </div>
    </div>

</div>

<div class="actions">
    <a href="quote_list.php" class="btn btn-back">Back to Quote List</a>
    <button onclick="window.print()" class="btn btn-print">Print Estimate</button>
</div>

</div>

</body>
</html>