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

$pageTitle = 'Consignment Intake (GRN)';
const CURIO_CATEGORY_ID = 1010;

if (!function_exists('h')) { function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('money_fmt')) { function money_fmt($v): string { return number_format((float)$v, 2); } }
if (!function_exists('cci_table_exists')) {
    function cci_table_exists(PDO $pdo, string $table): bool {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $s->execute([':t'=>$table]);
        return (int)$s->fetchColumn() > 0;
    }
}
if (!function_exists('cci_column_exists')) {
    function cci_column_exists(PDO $pdo, string $table, string $column): bool {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $s->execute([':t'=>$table, ':c'=>$column]);
        return (int)$s->fetchColumn() > 0;
    }
}
if (!function_exists('cci_flash')) { function cci_flash(string $type, string $message): void { $_SESSION['cci_flash'][]=['type'=>$type,'message'=>$message]; } }
if (!function_exists('cci_get_flash')) { function cci_get_flash(): array { $f=$_SESSION['cci_flash']??[]; unset($_SESSION['cci_flash']); return $f; } }
if (!function_exists('cci_user_id')) {
    function cci_user_id(): ?int {
        foreach (['user_id','ss_user_id','id','uid','UserID','userid'] as $k) if (!empty($_SESSION[$k])) return (int)$_SESSION[$k];
        if (!empty($_SESSION['user']) && is_array($_SESSION['user'])) {
            foreach (['id','user_id','UserID'] as $k) if (!empty($_SESSION['user'][$k])) return (int)$_SESSION['user'][$k];
        }
        return null;
    }
}
if (!function_exists('cci_no')) {
    function cci_no(PDO $pdo): string {
        $prefix = 'CIN-' . date('ymd') . '-';
        $s = $pdo->prepare("SELECT COUNT(*) FROM curio_consignment_intakes WHERE intake_no LIKE :p");
        $s->execute([':p'=>$prefix.'%']);
        return $prefix . str_pad((string)((int)$s->fetchColumn()+1), 4, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('cci_post_array')) {
    function cci_post_array(string $key): array {
        $v = $_POST[$key] ?? [];
        return is_array($v) ? array_values($v) : [$v];
    }
}
if (!function_exists('cci_float')) {
    function cci_float($v): float {
        $v = trim(str_replace(',', '', (string)$v));
        return ($v !== '' && is_numeric($v)) ? (float)$v : 0.0;
    }
}

$errors = [];
try {
    if (!cci_table_exists($pdo, 'curio_consignment')) {
        throw new RuntimeException('Open Curio Consignment Suppliers first so supplier/item terms can be configured.');
    }
    if (!cci_column_exists($pdo, 'curio_consignment', 'qty_received')) {
        $pdo->exec("ALTER TABLE curio_consignment ADD COLUMN qty_received DECIMAL(14,4) NOT NULL DEFAULT 0.0000 AFTER commission_pct");
    }

    $pdo->exec("CREATE TABLE IF NOT EXISTS curio_consignment_intakes (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        intake_no VARCHAR(60) NOT NULL,
        supplier_id INT UNSIGNED NOT NULL,
        supplier_name VARCHAR(180) NOT NULL,
        store_id INT UNSIGNED NULL,
        delivery_note_no VARCHAR(100) NULL,
        intake_date DATE NOT NULL,
        total_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_consignment_cost DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        status ENUM('posted','void') NOT NULL DEFAULT 'posted',
        notes TEXT NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        void_reason TEXT NULL,
        voided_by INT UNSIGNED NULL,
        voided_at DATETIME NULL,
        UNIQUE KEY uq_curio_consignment_intake_no (intake_no),
        INDEX idx_curio_consignment_intake_supplier (supplier_id),
        INDEX idx_curio_consignment_intake_date (intake_date),
        INDEX idx_curio_consignment_intake_store (store_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS curio_consignment_intake_lines (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        intake_id BIGINT UNSIGNED NOT NULL,
        item_id INT UNSIGNED NOT NULL,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        line_cost DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes VARCHAR(255) NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_curio_consignment_line_intake (intake_id),
        INDEX idx_curio_consignment_line_item (item_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare consignment intake: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();
        $action = (string)($_POST['action'] ?? '');

        if ($action === 'post_intake') {
            $supplierId = (int)($_POST['supplier_id'] ?? 0);
            $storeId = (int)($_POST['store_id'] ?? 0);
            $deliveryNote = trim((string)($_POST['delivery_note_no'] ?? ''));
            $intakeDate = trim((string)($_POST['intake_date'] ?? date('Y-m-d')));
            $notes = trim((string)($_POST['notes'] ?? ''));

            if ($supplierId <= 0) throw new RuntimeException('Please select a consignment supplier.');
            if (strtotime($intakeDate) === false) throw new RuntimeException('Please enter a valid intake date.');

            $s = $pdo->prepare("SELECT supplier_name FROM inventory_suppliers WHERE id=:id AND COALESCE(is_active,1)=1 LIMIT 1");
            $s->execute([':id'=>$supplierId]);
            $supplierName = trim((string)$s->fetchColumn());
            if ($supplierName === '') throw new RuntimeException('The selected supplier was not found or is inactive.');

            $itemIds = cci_post_array('item_id');
            $qtys = cci_post_array('qty');
            $costs = cci_post_array('unit_cost');
            $sellings = cci_post_array('selling_price');
            $lineNotes = cci_post_array('line_notes');
            $max = max(count($itemIds), count($qtys), count($costs), count($sellings));

            $lines = [];
            $totalQty = 0.0;
            $totalCost = 0.0;
            for ($i=0; $i<$max; $i++) {
                $itemId = (int)($itemIds[$i] ?? 0);
                $qty = round(cci_float($qtys[$i] ?? 0), 4);
                $unitCost = round(cci_float($costs[$i] ?? 0), 4);
                $selling = round(cci_float($sellings[$i] ?? 0), 4);
                $ln = trim((string)($lineNotes[$i] ?? ''));

                if ($itemId <= 0 && $qty <= 0 && $unitCost <= 0 && $selling <= 0) continue;
                $rowNo = $i + 1;
                if ($itemId <= 0) throw new RuntimeException("Line {$rowNo}: select a curio item.");
                if ($qty <= 0) throw new RuntimeException("Line {$rowNo}: quantity must be greater than zero.");
                if ($unitCost < 0 || $selling < 0) throw new RuntimeException("Line {$rowNo}: prices cannot be negative.");

                $st = $pdo->prepare("SELECT ii.id, ii.item_code, ii.item_name, ii.selling_price, cc.unit_cost, cc.supplier_id
                                     FROM inventory_items ii
                                     INNER JOIN curio_consignment cc ON cc.item_id=ii.id AND COALESCE(cc.is_active,1)=1
                                     WHERE ii.id=:item_id AND cc.supplier_id=:supplier_id LIMIT 1");
                $st->execute([':item_id'=>$itemId, ':supplier_id'=>$supplierId]);
                $item = $st->fetch(PDO::FETCH_ASSOC);
                if (!$item) throw new RuntimeException("Line {$rowNo}: this item is not assigned to the selected consignment supplier.");

                if ($unitCost <= 0) $unitCost = round((float)($item['unit_cost'] ?? 0), 4);
                if ($selling <= 0) $selling = round((float)($item['selling_price'] ?? 0), 4);
                $lineCost = round($qty * $unitCost, 2);
                $totalQty += $qty;
                $totalCost += $lineCost;
                $lines[] = [
                    'item_id'=>$itemId,
                    'item_code'=>(string)($item['item_code'] ?? ''),
                    'item_name'=>(string)($item['item_name'] ?? ''),
                    'qty'=>$qty,
                    'unit_cost'=>$unitCost,
                    'selling_price'=>$selling,
                    'line_cost'=>$lineCost,
                    'notes'=>$ln !== '' ? $ln : null,
                ];
            }
            if (!$lines) throw new RuntimeException('Please add at least one consignment item.');

            $pdo->beginTransaction();
            $intakeNo = cci_no($pdo);
            $ins = $pdo->prepare("INSERT INTO curio_consignment_intakes
                (intake_no,supplier_id,supplier_name,store_id,delivery_note_no,intake_date,total_qty,total_consignment_cost,status,notes,created_by)
                VALUES (:no,:sid,:sname,:store,:dn,:dt,:qty,:cost,'posted',:notes,:uid)");
            $ins->execute([
                ':no'=>$intakeNo, ':sid'=>$supplierId, ':sname'=>$supplierName,
                ':store'=>$storeId > 0 ? $storeId : null,
                ':dn'=>$deliveryNote !== '' ? $deliveryNote : null,
                ':dt'=>date('Y-m-d', strtotime($intakeDate)), ':qty'=>round($totalQty,4),
                ':cost'=>round($totalCost,2), ':notes'=>$notes !== '' ? $notes : null,
                ':uid'=>cci_user_id(),
            ]);
            $intakeId = (int)$pdo->lastInsertId();

            $lineIns = $pdo->prepare("INSERT INTO curio_consignment_intake_lines
                (intake_id,item_id,item_code,item_name,qty,unit_cost,selling_price,line_cost,notes)
                VALUES (:iid,:item,:code,:name,:qty,:cost,:selling,:line_cost,:notes)");
            $balanceUpd = $pdo->prepare("UPDATE curio_consignment
                                        SET qty_received=COALESCE(qty_received,0)+:qty,
                                            unit_cost=:cost,
                                            updated_at=CURRENT_TIMESTAMP
                                        WHERE item_id=:item AND supplier_id=:supplier");
            foreach ($lines as $line) {
                $lineIns->execute([
                    ':iid'=>$intakeId, ':item'=>$line['item_id'], ':code'=>$line['item_code'] ?: null,
                    ':name'=>$line['item_name'], ':qty'=>$line['qty'], ':cost'=>$line['unit_cost'],
                    ':selling'=>$line['selling_price'], ':line_cost'=>$line['line_cost'], ':notes'=>$line['notes'],
                ]);
                $balanceUpd->execute([
                    ':qty'=>$line['qty'], ':cost'=>$line['unit_cost'], ':item'=>$line['item_id'], ':supplier'=>$supplierId,
                ]);
                if ($balanceUpd->rowCount() === 0) throw new RuntimeException('Could not update consignment balance for ' . $line['item_name'] . '.');
            }
            $pdo->commit();
            cci_flash('success', 'Consignment intake posted successfully: ' . $intakeNo . '. Supplier-owned stock was not added to owned inventory value.');
            header('Location: curio_consignment_intake.php?view_id=' . $intakeId);
            exit;
        }

        if ($action === 'void_intake') {
            $intakeId = (int)($_POST['intake_id'] ?? 0);
            $reason = trim((string)($_POST['void_reason'] ?? ''));
            if ($intakeId <= 0) throw new RuntimeException('Invalid consignment intake.');
            if ($reason === '') throw new RuntimeException('Void reason is required.');

            $st = $pdo->prepare("SELECT * FROM curio_consignment_intakes WHERE id=:id LIMIT 1");
            $st->execute([':id'=>$intakeId]);
            $doc = $st->fetch(PDO::FETCH_ASSOC);
            if (!$doc) throw new RuntimeException('Consignment intake not found.');
            if (($doc['status'] ?? '') === 'void') throw new RuntimeException('This intake is already void.');

            $ls = $pdo->prepare("SELECT * FROM curio_consignment_intake_lines WHERE intake_id=:id");
            $ls->execute([':id'=>$intakeId]);
            $lines = $ls->fetchAll(PDO::FETCH_ASSOC);

            $pdo->beginTransaction();
            $upd = $pdo->prepare("UPDATE curio_consignment
                                  SET qty_received=GREATEST(0,COALESCE(qty_received,0)-:qty), updated_at=CURRENT_TIMESTAMP
                                  WHERE item_id=:item AND supplier_id=:supplier");
            foreach ($lines as $line) {
                $upd->execute([':qty'=>(float)$line['qty'], ':item'=>(int)$line['item_id'], ':supplier'=>(int)$doc['supplier_id']]);
            }
            $pdo->prepare("UPDATE curio_consignment_intakes
                           SET status='void', void_reason=:reason, voided_by=:uid, voided_at=NOW()
                           WHERE id=:id")
                ->execute([':reason'=>$reason, ':uid'=>cci_user_id(), ':id'=>$intakeId]);
            $pdo->commit();
            cci_flash('success', 'Consignment intake voided and supplier-owned quantities reversed.');
            header('Location: curio_consignment_intake.php?view_id=' . $intakeId);
            exit;
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        cci_flash('danger', $e->getMessage());
        header('Location: curio_consignment_intake.php');
        exit;
    }
}

$suppliers = [];
$stores = [];
$configuredItems = [];
try {
    $suppliers = $pdo->query("SELECT DISTINCT s.id,s.supplier_name
                              FROM inventory_suppliers s
                              INNER JOIN curio_consignment cc ON cc.supplier_id=s.id AND COALESCE(cc.is_active,1)=1
                              WHERE COALESCE(s.is_active,1)=1 ORDER BY s.supplier_name")
                     ->fetchAll(PDO::FETCH_ASSOC);
    if (cci_table_exists($pdo, 'store_locations')) {
        $stores = $pdo->query("SELECT id,location_name FROM store_locations WHERE COALESCE(is_active,1)=1 ORDER BY location_name")
                      ->fetchAll(PDO::FETCH_ASSOC);
    }
    $configuredItems = $pdo->query("SELECT ii.id,ii.item_code,ii.item_name,ii.selling_price,
                                           cc.supplier_id,cc.unit_cost,cc.qty_received,s.supplier_name
                                    FROM curio_consignment cc
                                    INNER JOIN inventory_items ii ON ii.id=cc.item_id
                                    INNER JOIN inventory_suppliers s ON s.id=cc.supplier_id
                                    WHERE COALESCE(cc.is_active,1)=1 AND COALESCE(ii.is_active,1)=1
                                    ORDER BY s.supplier_name,ii.item_name")
                           ->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $errors[]='Could not load form data: '.$e->getMessage(); }

$dateFrom = trim((string)($_GET['date_from'] ?? date('Y-m-01')));
$dateTo = trim((string)($_GET['date_to'] ?? date('Y-m-d')));
$supplierFilter = (int)($_GET['supplier_id'] ?? 0);
$statusFilter = trim((string)($_GET['status'] ?? ''));
$q = trim((string)($_GET['q'] ?? ''));
if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-01');
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d');
$where = 'ci.intake_date BETWEEN :df AND :dt';
$params = [':df'=>$dateFrom, ':dt'=>$dateTo];
if ($supplierFilter > 0) { $where .= ' AND ci.supplier_id=:sid'; $params[':sid']=$supplierFilter; }
if ($statusFilter !== '') { $where .= ' AND ci.status=:status'; $params[':status']=$statusFilter; }
if ($q !== '') { $where .= ' AND (ci.intake_no LIKE :q OR ci.delivery_note_no LIKE :q OR ci.supplier_name LIKE :q)'; $params[':q']='%'.$q.'%'; }

$history = [];
try {
    $st = $pdo->prepare("SELECT ci.*,sl.location_name,COUNT(cil.id) line_count
                         FROM curio_consignment_intakes ci
                         LEFT JOIN store_locations sl ON sl.id=ci.store_id
                         LEFT JOIN curio_consignment_intake_lines cil ON cil.intake_id=ci.id
                         WHERE {$where}
                         GROUP BY ci.id ORDER BY ci.intake_date DESC,ci.id DESC LIMIT 300");
    $st->execute($params);
    $history = $st->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $errors[]='Could not load consignment history: '.$e->getMessage(); }

$viewId = (int)($_GET['view_id'] ?? 0);
$viewDoc = null;
$viewLines = [];
if ($viewId > 0) {
    try {
        $st = $pdo->prepare("SELECT ci.*,sl.location_name FROM curio_consignment_intakes ci LEFT JOIN store_locations sl ON sl.id=ci.store_id WHERE ci.id=:id LIMIT 1");
        $st->execute([':id'=>$viewId]);
        $viewDoc = $st->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($viewDoc) {
            $st = $pdo->prepare("SELECT * FROM curio_consignment_intake_lines WHERE intake_id=:id ORDER BY id");
            $st->execute([':id'=>$viewId]);
            $viewLines = $st->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) { $errors[]='Could not load intake detail: '.$e->getMessage(); }
}

$flashes = cci_get_flash();
require_once __DIR__ . '/../../includes/header.php';
?>
<style>
.cci-hero{background:linear-gradient(135deg,#102a43,#176b87);border-radius:18px;padding:28px;color:#fff;margin-bottom:22px}.cci-card{border:0;border-radius:16px;box-shadow:0 10px 30px rgba(15,23,42,.08)}.cci-table thead th{background:#eef4f8;color:#334e68;font-size:.78rem;text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}.cci-protection{border-left:4px solid #0ea5e9;background:#f0f9ff}.cci-summary{background:#f8fafc;border-radius:12px;padding:14px}.cci-item-search{min-width:280px}.cci-muted{font-size:.82rem;color:#64748b}@media print{.no-print,header,nav,footer,.sidebar{display:none!important}.cci-card{box-shadow:none}.cci-hero{background:#fff!important;color:#000!important;padding:0}.container-fluid{width:100%!important}}
</style>

<div class="cci-hero d-flex flex-wrap justify-content-between align-items-center gap-3">
    <div>
        <div class="small text-white-50 text-uppercase fw-bold">Supplier-owned stock</div>
        <h2 class="mb-1">Consignment Intake (GRN)</h2>
        <div class="text-white-50">Receive multiple consignment curios in one controlled document.</div>
    </div>
    <div class="no-print">
        <a href="curio_consignment.php" class="btn btn-light"><i class="bi bi-gear me-2"></i>Suppliers &amp; Terms</a>
        <a href="curio_consignment_sales_report.php" class="btn btn-outline-light"><i class="bi bi-graph-up me-2"></i>Sales Report</a>
    </div>
</div>

<?php foreach ($flashes as $f): ?><div class="alert alert-<?php echo h($f['type']); ?>"><?php echo h($f['message']); ?></div><?php endforeach; ?>
<?php if ($errors): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo h($e); ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<div class="alert cci-protection mb-4">
    <strong><i class="bi bi-shield-check me-2"></i>Valuation protected.</strong>
    This intake updates only consignment custody and supplier balances. It does not create a normal GRN movement and does not add supplier-owned goods to your owned inventory value.
</div>

<div class="card cci-card mb-4 no-print">
    <div class="card-header bg-white border-0 pt-4 px-4"><h5 class="mb-0">New Consignment Intake</h5></div>
    <div class="card-body p-4">
        <form method="post" id="intakeForm">
            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
            <input type="hidden" name="action" value="post_intake">
            <div class="row g-3 mb-4">
                <div class="col-lg-3"><label class="form-label">Supplier <span class="text-danger">*</span></label><select name="supplier_id" id="supplierId" class="form-select" required><option value="">Select supplier</option><?php foreach($suppliers as $s): ?><option value="<?php echo (int)$s['id']; ?>"><?php echo h($s['supplier_name']); ?></option><?php endforeach; ?></select></div>
                <div class="col-lg-2"><label class="form-label">Intake Date</label><input type="date" name="intake_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required></div>
                <div class="col-lg-2"><label class="form-label">Delivery Note</label><input type="text" name="delivery_note_no" class="form-control" placeholder="Supplier reference"></div>
                <div class="col-lg-2"><label class="form-label">Receiving Location</label><select name="store_id" class="form-select"><option value="0">Not specified</option><?php foreach($stores as $s): ?><option value="<?php echo (int)$s['id']; ?>"><?php echo h($s['location_name']); ?></option><?php endforeach; ?></select></div>
                <div class="col-lg-3"><label class="form-label">Header Notes</label><input type="text" name="notes" class="form-control" placeholder="Condition, cartons, receiver notes"></div>
            </div>

            <div class="table-responsive border rounded-3">
                <table class="table cci-table align-middle mb-0" id="lineTable">
                    <thead><tr><th style="min-width:280px">Curio Item</th><th class="text-end" style="width:130px">Qty Received</th><th class="text-end" style="width:140px">Supplier Cost</th><th class="text-end" style="width:140px">Selling Price</th><th class="text-end" style="width:140px">Consignment Value</th><th style="min-width:180px">Notes</th><th style="width:55px"></th></tr></thead>
                    <tbody id="lineBody"></tbody>
                    <tfoot><tr><td colspan="4" class="text-end fw-bold">Totals</td><td class="text-end fw-bold" id="grandValue">0.00</td><td colspan="2"><span class="cci-muted" id="grandQty">0 quantity</span></td></tr></tfoot>
                </table>
            </div>
            <div class="d-flex justify-content-between align-items-center mt-3">
                <button type="button" class="btn btn-outline-primary" id="addLine"><i class="bi bi-plus-circle me-2"></i>Add Item</button>
                <button type="submit" class="btn btn-primary px-4"><i class="bi bi-box-arrow-in-down me-2"></i>Receive Consignment</button>
            </div>
        </form>
    </div>
</div>

<?php if ($viewDoc): ?>
<div class="card cci-card mb-4" id="intakeDetail">
    <div class="card-header bg-white border-0 p-4 d-flex justify-content-between align-items-start">
        <div><div class="text-muted small">CONSIGNMENT INTAKE NOTE</div><h4 class="mb-1"><?php echo h($viewDoc['intake_no']); ?></h4><span class="badge bg-<?php echo $viewDoc['status']==='posted'?'success':'secondary'; ?>"><?php echo h(strtoupper($viewDoc['status'])); ?></span></div>
        <button onclick="window.print()" class="btn btn-outline-secondary no-print"><i class="bi bi-printer me-2"></i>Print</button>
    </div>
    <div class="card-body px-4 pb-4">
        <div class="row g-3 mb-4">
            <div class="col-md-3"><div class="cci-muted">Supplier</div><strong><?php echo h($viewDoc['supplier_name']); ?></strong></div>
            <div class="col-md-2"><div class="cci-muted">Date</div><strong><?php echo h($viewDoc['intake_date']); ?></strong></div>
            <div class="col-md-2"><div class="cci-muted">Delivery Note</div><strong><?php echo h($viewDoc['delivery_note_no'] ?: '—'); ?></strong></div>
            <div class="col-md-2"><div class="cci-muted">Location</div><strong><?php echo h($viewDoc['location_name'] ?: '—'); ?></strong></div>
            <div class="col-md-3"><div class="cci-muted">Consignment Value</div><strong><?php echo money_fmt($viewDoc['total_consignment_cost']); ?></strong></div>
        </div>
        <div class="table-responsive"><table class="table cci-table"><thead><tr><th>Item</th><th class="text-end">Qty</th><th class="text-end">Supplier Cost</th><th class="text-end">Selling Price</th><th class="text-end">Value</th><th>Notes</th></tr></thead><tbody><?php foreach($viewLines as $l): ?><tr><td><strong><?php echo h($l['item_name']); ?></strong><div class="cci-muted"><?php echo h($l['item_code']); ?></div></td><td class="text-end"><?php echo number_format((float)$l['qty'],4,'.',''); ?></td><td class="text-end"><?php echo money_fmt($l['unit_cost']); ?></td><td class="text-end"><?php echo money_fmt($l['selling_price']); ?></td><td class="text-end"><?php echo money_fmt($l['line_cost']); ?></td><td><?php echo h($l['notes'] ?: '—'); ?></td></tr><?php endforeach; ?></tbody></table></div>
        <?php if (!empty($viewDoc['notes'])): ?><div class="mt-3"><div class="cci-muted">Notes</div><?php echo nl2br(h($viewDoc['notes'])); ?></div><?php endif; ?>
        <?php if ($viewDoc['status']==='void'): ?><div class="alert alert-secondary mt-3"><strong>Void reason:</strong> <?php echo h($viewDoc['void_reason']); ?></div><?php endif; ?>
        <?php if ($viewDoc['status']==='posted'): ?><form method="post" class="mt-4 no-print" onsubmit="return confirm('Void this entire consignment intake and reverse its quantities?');"><?php if(function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="void_intake"><input type="hidden" name="intake_id" value="<?php echo (int)$viewDoc['id']; ?>"><div class="row g-2"><div class="col-md-9"><input type="text" name="void_reason" class="form-control" required placeholder="Reason for voiding"></div><div class="col-md-3 d-grid"><button class="btn btn-outline-danger">Void Intake</button></div></div></form><?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="card cci-card no-print">
    <div class="card-header bg-white border-0 pt-4 px-4"><h5 class="mb-0">Consignment Intake History</h5></div>
    <div class="card-body px-4 pt-3">
        <form method="get" class="row g-2 mb-3">
            <div class="col-md-2"><input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>"></div>
            <div class="col-md-2"><input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>"></div>
            <div class="col-md-3"><select name="supplier_id" class="form-select"><option value="0">All suppliers</option><?php foreach($suppliers as $s): ?><option value="<?php echo (int)$s['id']; ?>" <?php echo $supplierFilter===(int)$s['id']?'selected':''; ?>><?php echo h($s['supplier_name']); ?></option><?php endforeach; ?></select></div>
            <div class="col-md-2"><select name="status" class="form-select"><option value="">All statuses</option><option value="posted" <?php echo $statusFilter==='posted'?'selected':''; ?>>Posted</option><option value="void" <?php echo $statusFilter==='void'?'selected':''; ?>>Void</option></select></div>
            <div class="col-md-2"><input type="text" name="q" class="form-control" value="<?php echo h($q); ?>" placeholder="No, supplier, delivery note"></div>
            <div class="col-md-1 d-grid"><button class="btn btn-primary"><i class="bi bi-search"></i></button></div>
        </form>
        <div class="table-responsive"><table class="table cci-table align-middle"><thead><tr><th>Date</th><th>Intake No</th><th>Supplier</th><th>Delivery Note</th><th>Location</th><th class="text-end">Lines</th><th class="text-end">Qty</th><th class="text-end">Value</th><th>Status</th></tr></thead><tbody><?php if(!$history): ?><tr><td colspan="9" class="text-center text-muted py-4">No consignment intakes found.</td></tr><?php else: foreach($history as $r): ?><tr><td><?php echo h($r['intake_date']); ?></td><td><a href="?view_id=<?php echo (int)$r['id']; ?>"><?php echo h($r['intake_no']); ?></a></td><td><?php echo h($r['supplier_name']); ?></td><td><?php echo h($r['delivery_note_no'] ?: '—'); ?></td><td><?php echo h($r['location_name'] ?: '—'); ?></td><td class="text-end"><?php echo (int)$r['line_count']; ?></td><td class="text-end"><?php echo number_format((float)$r['total_qty'],4,'.',''); ?></td><td class="text-end"><?php echo money_fmt($r['total_consignment_cost']); ?></td><td><span class="badge bg-<?php echo $r['status']==='posted'?'success':'secondary'; ?>"><?php echo h($r['status']); ?></span></td></tr><?php endforeach; endif; ?></tbody></table></div>
    </div>
</div>

<script>
const allItems = <?php echo json_encode($configuredItems, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); ?>;
const body = document.getElementById('lineBody');
const supplier = document.getElementById('supplierId');
function esc(v){return String(v??'').replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]));}
function optionsForSupplier(selected=''){
  const sid = Number(supplier.value||0);
  let out='<option value="">Select item</option>';
  allItems.filter(x=>Number(x.supplier_id)===sid).forEach(x=>{out+=`<option value="${x.id}" data-cost="${x.unit_cost}" data-selling="${x.selling_price}" ${String(x.id)===String(selected)?'selected':''}>${esc(x.item_name)}${x.item_code?' ['+esc(x.item_code)+']':''}</option>`;});
  return out;
}
function addLine(){
  if(!supplier.value){alert('Select the supplier first.'); supplier.focus(); return;}
  const tr=document.createElement('tr');
  tr.innerHTML=`<td><select name="item_id[]" class="form-select item-select" required>${optionsForSupplier()}</select><div class="cci-muted onhand"></div></td><td><input name="qty[]" type="number" min="0.0001" step="0.0001" class="form-control text-end qty" required></td><td><input name="unit_cost[]" type="number" min="0" step="0.0001" class="form-control text-end cost"></td><td><input name="selling_price[]" type="number" min="0" step="0.0001" class="form-control text-end selling"></td><td class="text-end fw-semibold line-value">0.00</td><td><input name="line_notes[]" class="form-control" placeholder="Optional"></td><td><button type="button" class="btn btn-sm btn-outline-danger remove-line"><i class="bi bi-x-lg"></i></button></td>`;
  body.appendChild(tr); bindRow(tr); recalc();
}
function bindRow(tr){
  tr.querySelector('.item-select').addEventListener('change',function(){
    const item=allItems.find(x=>String(x.id)===String(this.value));
    if(item){tr.querySelector('.cost').value=Number(item.unit_cost||0).toFixed(4);tr.querySelector('.selling').value=Number(item.selling_price||0).toFixed(4);tr.querySelector('.onhand').textContent='Current received balance: '+Number(item.qty_received||0).toFixed(4);} recalc();
  });
  tr.querySelectorAll('.qty,.cost,.selling').forEach(el=>el.addEventListener('input',recalc));
  tr.querySelector('.remove-line').addEventListener('click',()=>{tr.remove();recalc();});
}
function recalc(){let qty=0,val=0;body.querySelectorAll('tr').forEach(tr=>{const q=Number(tr.querySelector('.qty').value||0),c=Number(tr.querySelector('.cost').value||0),v=q*c;qty+=q;val+=v;tr.querySelector('.line-value').textContent=v.toFixed(2);});document.getElementById('grandValue').textContent=val.toFixed(2);document.getElementById('grandQty').textContent=qty.toFixed(4)+' quantity';}
document.getElementById('addLine').addEventListener('click',addLine);
supplier.addEventListener('change',()=>{body.innerHTML=''; if(supplier.value) addLine();});
document.getElementById('intakeForm').addEventListener('submit',e=>{if(!body.querySelector('tr')){e.preventDefault();alert('Add at least one item.');}});
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
