<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    exit('Invalid Goods Returned Note.');
}

$stmt = $pdo->prepare("
    SELECT sr.*, sl.location_name
    FROM inventory_supplier_returns sr
    LEFT JOIN store_locations sl ON sl.id=sr.store_id
    WHERE sr.id=:id LIMIT 1
");
$stmt->execute([':id'=>$id]);
$doc = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$doc) {
    http_response_code(404);
    exit('Goods Returned Note not found.');
}

$stmt = $pdo->prepare("
    SELECT srl.*, ii.item_code, ii.item_name, iu.unit_code
    FROM inventory_supplier_return_lines srl
    INNER JOIN inventory_items ii ON ii.id=srl.item_id
    LEFT JOIN inventory_units iu ON iu.id=ii.unit_id
    WHERE srl.return_id=:return_id
    ORDER BY srl.id
");
$stmt->execute([':return_id'=>$id]);
$lines = $stmt->fetchAll(PDO::FETCH_ASSOC);

$supplier = null;
if ((int)$doc['supplier_id'] > 0) {
    $stmt = $pdo->prepare("SELECT * FROM inventory_suppliers WHERE id=:id LIMIT 1");
    $stmt->execute([':id'=>(int)$doc['supplier_id']]);
    $supplier = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= h($doc['return_no']) ?> - Supplier Credit Note</title>
<style>
body{font-family:Arial,sans-serif;color:#172033;margin:0;background:#eef2f7}
.page{width:210mm;min-height:297mm;margin:12px auto;background:#fff;padding:16mm;box-sizing:border-box;box-shadow:0 10px 35px rgba(0,0,0,.12)}
.header{display:flex;justify-content:space-between;gap:30px;border-bottom:3px solid #c92a2a;padding-bottom:14px}
.title h1{font-size:24px;margin:0;color:#c92a2a}.title div{margin-top:5px;color:#667085}
.docno{text-align:right}.docno strong{display:block;font-size:20px}.docno span{font-size:12px;color:#667085}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin:20px 0}.box{border:1px solid #dfe4eb;border-radius:8px;padding:12px}.box h3{font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#667085;margin:0 0 8px}
table{width:100%;border-collapse:collapse;margin-top:16px}th{background:#f3f5f8;font-size:11px;text-transform:uppercase;text-align:left;padding:9px;border-bottom:1px solid #ccd4df}td{font-size:12px;padding:9px;border-bottom:1px solid #e7ebf0;vertical-align:top}.right{text-align:right}
.totals{width:310px;margin-left:auto;margin-top:18px}.totals div{display:flex;justify-content:space-between;padding:7px 0}.totals .grand{border-top:2px solid #c92a2a;margin-top:4px;padding-top:12px;font-size:17px;font-weight:bold;color:#c92a2a}
.notes{margin-top:24px;padding:12px;border:1px solid #dfe4eb;border-radius:8px;font-size:12px}.signatures{display:grid;grid-template-columns:1fr 1fr 1fr;gap:30px;margin-top:55px}.sig{border-top:1px solid #333;padding-top:7px;font-size:11px;color:#667085}
.no-print{position:fixed;right:20px;top:20px}.btn{border:0;border-radius:7px;padding:10px 16px;background:#0d6efd;color:#fff;font-weight:bold;cursor:pointer}
.void{display:inline-block;padding:5px 10px;border:2px solid #b42318;color:#b42318;font-weight:bold;transform:rotate(-5deg)}
@media print{body{background:#fff}.page{margin:0;box-shadow:none;width:auto;min-height:auto}.no-print{display:none}}
</style>
</head>
<body>
<div class="no-print"><button class="btn" onclick="window.print()">Print</button></div>
<div class="page">
    <div class="header">
        <div class="title">
            <h1>Goods Returned Note</h1>
            <div>Supplier Credit Note / Stock Return</div>
        </div>
        <div class="docno">
            <strong><?= h($doc['return_no']) ?></strong>
            <span><?= h($doc['return_date']) ?></span>
            <?php if ($doc['status'] === 'void'): ?><div class="void">VOID</div><?php endif; ?>
        </div>
    </div>

    <div class="grid">
        <div class="box">
            <h3>Supplier</h3>
            <strong><?= h($doc['supplier_name']) ?></strong><br>
            <?php if ($supplier): ?>
                <?= h($supplier['address'] ?? '') ?><br>
                <?= h($supplier['phone'] ?? '') ?><br>
                <?= h($supplier['email'] ?? '') ?>
            <?php endif; ?>
        </div>
        <div class="box">
            <h3>Return Details</h3>
            <strong>Store:</strong> <?= h($doc['location_name']) ?><br>
            <strong>Original GRN:</strong> <?= h($doc['original_grn_no'] ?: 'N/A') ?><br>
            <strong>Supplier Credit Note:</strong> <?= h($doc['supplier_credit_note_no'] ?: 'Pending / Not supplied') ?><br>
            <strong>Reason:</strong> <?= h($doc['reason'] ?: 'Not specified') ?>
        </div>
    </div>

    <table>
        <thead>
        <tr>
            <th>Code</th>
            <th>Item</th>
            <th class="right">Qty</th>
            <th>Unit</th>
            <th class="right">Unit Cost</th>
            <th class="right">Tax</th>
            <th class="right">Line Total</th>
            <th>Reason</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($lines as $line): ?>
            <tr>
                <td><?= h($line['item_code']) ?></td>
                <td><?= h($line['item_name']) ?></td>
                <td class="right"><?= number_format((float)$line['qty'],4) ?></td>
                <td><?= h($line['unit_code']) ?></td>
                <td class="right"><?= number_format((float)$line['unit_cost'],4) ?></td>
                <td class="right"><?= money_fmt($line['line_tax']) ?></td>
                <td class="right"><?= money_fmt($line['line_total']) ?></td>
                <td><?= h($line['reason']) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <div class="totals">
        <div><span>Subtotal</span><strong><?= money_fmt($doc['subtotal']) ?></strong></div>
        <div><span>Tax</span><strong><?= money_fmt($doc['tax_amount']) ?></strong></div>
        <div class="grand"><span>Supplier Credit Total</span><span><?= money_fmt($doc['total_amount']) ?></span></div>
    </div>

    <?php if (!empty($doc['notes'])): ?>
        <div class="notes"><strong>Notes:</strong><br><?= nl2br(h($doc['notes'])) ?></div>
    <?php endif; ?>

    <div class="signatures">
        <div class="sig">Prepared By</div>
        <div class="sig">Stores / Inventory</div>
        <div class="sig">Supplier Acknowledgement</div>
    </div>
</div>
</body>
</html>
