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

$pageTitle = 'Curio Consignment Suppliers';

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($a): string { return number_format((float)$a, 2); }
}
if (!function_exists('cc_table_exists')) {
    function cc_table_exists(PDO $pdo, string $t): bool {
        $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $s->execute([':t' => $t]);
        return (int)$s->fetchColumn() > 0;
    }
}
if (!function_exists('cc_col')) {
    function cc_col(PDO $pdo, string $t, array $cands): ?string {
        foreach ($cands as $c) {
            $s = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
            $s->execute([':t' => $t, ':c' => $c]);
            if ((int)$s->fetchColumn() > 0) return $c;
        }
        return null;
    }
}
if (!function_exists('cc_flash')) {
    function cc_flash(string $type, string $msg): void { $_SESSION['cc_flash'][] = ['type'=>$type,'message'=>$msg]; }
}
if (!function_exists('cc_get_flash')) {
    function cc_get_flash(): array { $x = $_SESSION['cc_flash'] ?? []; unset($_SESSION['cc_flash']); return $x; }
}

$errors = [];

/* Junction table: one consignment link per curio item, with cost owed, optional commission, and running received qty. */
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS curio_consignment (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        supplier_id INT UNSIGNED NOT NULL,
        unit_cost DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        commission_pct DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        qty_received DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        notes VARCHAR(255) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_curio_consignment_item (item_id),
        INDEX idx_curio_consignment_supplier (supplier_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    /* Existing installs created before phase 2: add the running received qty. */
    if (!cc_col($pdo, 'curio_consignment', ['qty_received'])) {
        $pdo->exec("ALTER TABLE curio_consignment ADD COLUMN qty_received DECIMAL(14,2) NOT NULL DEFAULT 0.00 AFTER commission_pct");
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare consignment table: ' . $e->getMessage();
}

$hasSuppliers = cc_table_exists($pdo, 'inventory_suppliers');
$hasItems     = cc_table_exists($pdo, 'inventory_items');

/* Save one item's consignment settings. */
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();
        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_consignment') {
            $itemId       = (int)($_POST['item_id'] ?? 0);
            $supplierId   = (int)($_POST['supplier_id'] ?? 0);
            $unitCost     = round((float)($_POST['unit_cost'] ?? 0), 2);
            $commission   = round((float)($_POST['commission_pct'] ?? 0), 4);
            $qtyReceived  = round((float)($_POST['qty_received'] ?? 0), 2);
            $notes        = trim((string)($_POST['notes'] ?? ''));

            if ($itemId <= 0) throw new RuntimeException('Invalid curio item.');
            if ($unitCost < 0) throw new RuntimeException('Unit cost cannot be negative.');
            if ($commission < 0 || $commission > 100) throw new RuntimeException('Commission must be between 0 and 100%.');
            if ($qtyReceived < 0) throw new RuntimeException('Received quantity cannot be negative.');

            if ($supplierId <= 0) {
                /* Clearing the supplier removes the consignment link for this item. */
                $pdo->prepare("DELETE FROM curio_consignment WHERE item_id=:i")->execute([':i'=>$itemId]);
                cc_flash('success', 'Consignment supplier cleared for this curio.');
            } else {
                $pdo->prepare("
                    INSERT INTO curio_consignment (item_id, supplier_id, unit_cost, commission_pct, qty_received, notes, is_active)
                    VALUES (:i, :s, :c, :p, :q, :n, 1)
                    ON DUPLICATE KEY UPDATE
                        supplier_id=VALUES(supplier_id),
                        unit_cost=VALUES(unit_cost),
                        commission_pct=VALUES(commission_pct),
                        qty_received=VALUES(qty_received),
                        notes=VALUES(notes),
                        is_active=1
                ")->execute([
                    ':i'=>$itemId, ':s'=>$supplierId, ':c'=>$unitCost, ':p'=>$commission,
                    ':q'=>$qtyReceived, ':n'=>$notes !== '' ? $notes : null,
                ]);
                cc_flash('success', 'Consignment supplier saved.');
            }
            header('Location: curio_consignment.php' . (isset($_POST['q']) && $_POST['q'] !== '' ? '?q=' . urlencode((string)$_POST['q']) : ''));
            exit;
        }
    } catch (Throwable $e) {
        cc_flash('danger', $e->getMessage());
        header('Location: curio_consignment.php');
        exit;
    }
}

/* Suppliers for the dropdowns. */
$suppliers = [];
if ($hasSuppliers) {
    $suppliers = $pdo->query("
        SELECT id, supplier_name
        FROM inventory_suppliers
        WHERE COALESCE(is_active,1)=1
        ORDER BY supplier_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
}

/* Load all curio (category 1010) items, with any existing consignment link. */
$q = trim((string)($_GET['q'] ?? ''));
$curios = [];
if ($hasItems) {
    $nameCol = cc_col($pdo, 'inventory_items', ['item_name','name','description']) ?: 'id';
    $codeCol = cc_col($pdo, 'inventory_items', ['item_code','code','sku']);
    $catCol  = cc_col($pdo, 'inventory_items', ['category_id','inventory_category_id','category']) ?: 'category_id';
    $activeCol = cc_col($pdo, 'inventory_items', ['is_active','active']);

    $codeExpr = $codeCol ? "ii.`$codeCol`" : "''";
    $where = "ii.`$catCol` = :cat";
    $params = [':cat' => CURIO_CATEGORY_ID];
    if ($activeCol) $where .= " AND COALESCE(ii.`$activeCol`,1)=1";
    if ($q !== '') {
        $where .= " AND (ii.`$nameCol` LIKE :q1 OR $codeExpr LIKE :q2)";
        $params[':q1'] = '%'.$q.'%';
        $params[':q2'] = '%'.$q.'%';
    }

    $sql = "SELECT ii.id,
                   ii.`$nameCol` AS item_name,
                   $codeExpr AS item_code,
                   cc.supplier_id, cc.unit_cost, cc.commission_pct, cc.qty_received, cc.notes,
                   sup.supplier_name
            FROM inventory_items ii
            LEFT JOIN curio_consignment cc ON cc.item_id = ii.id AND COALESCE(cc.is_active,1)=1
            LEFT JOIN inventory_suppliers sup ON sup.id = cc.supplier_id
            WHERE $where
            ORDER BY ii.`$nameCol` ASC
            LIMIT 2000";
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $curios = $st->fetchAll(PDO::FETCH_ASSOC);
}

$configuredCount = 0;
foreach ($curios as $c) if (!empty($c['supplier_id'])) $configuredCount++;

$flashes = cc_get_flash();
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-bag-heart"></i> Curio Consignment</div>
            <div class="hero-title mt-2">Curio Consignment Suppliers</div>
            <div class="hero-subtitle mt-2">Set the consignment supplier, unit cost owed and optional commission for each curio (category <?php echo CURIO_CATEGORY_ID; ?>).</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="curio_consignment_sales_report.php" class="btn btn-light"><i class="bi bi-graph-up me-2"></i>Sales Report</a>
        </div>
    </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; ?>

<?php if (!$hasSuppliers): ?>
    <div class="alert alert-warning">No <code>inventory_suppliers</code> table found. Add suppliers on the Suppliers page first.</div>
<?php endif; ?>

<div class="card panel-card mb-3">
    <div class="card-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-9">
                <label class="form-label">Search Curios</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($q); ?>" placeholder="Curio name or code">
            </div>
            <div class="col-md-3 d-grid">
                <button class="btn btn-primary"><i class="bi bi-search me-2"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Curio Items (<?php echo count($curios); ?>) — <?php echo $configuredCount; ?> on consignment</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                    <tr>
                        <th>Curio Item</th>
                        <th style="width:230px;">Consignment Supplier</th>
                        <th class="text-end" style="width:130px;">Unit Cost</th>
                        <th class="text-end" style="width:120px;">Commission %</th>
                        <th class="text-end" style="width:120px;">Qty Received</th>
                        <th style="width:110px;"></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$curios): ?>
                        <tr><td colspan="6" class="text-center text-muted py-4">No curio items found under category <?php echo CURIO_CATEGORY_ID; ?>.</td></tr>
                    <?php else: ?>
                        <?php foreach ($curios as $it): ?>
                            <tr>
                                <form method="post">
                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                    <input type="hidden" name="action" value="save_consignment">
                                    <input type="hidden" name="item_id" value="<?php echo (int)$it['id']; ?>">
                                    <input type="hidden" name="q" value="<?php echo h($q); ?>">
                                    <td>
                                        <strong><?php echo h($it['item_name']); ?></strong>
                                        <?php if (!empty($it['item_code'])): ?><div class="small text-muted"><?php echo h($it['item_code']); ?></div><?php endif; ?>
                                    </td>
                                    <td>
                                        <select name="supplier_id" class="form-select form-select-sm">
                                            <option value="0">— None (not on consignment) —</option>
                                            <?php foreach ($suppliers as $s): ?>
                                                <option value="<?php echo (int)$s['id']; ?>" <?php echo (int)($it['supplier_id'] ?? 0) === (int)$s['id'] ? 'selected' : ''; ?>>
                                                    <?php echo h($s['supplier_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="number" step="0.01" min="0" name="unit_cost" class="form-control form-control-sm text-end" value="<?php echo h(number_format((float)($it['unit_cost'] ?? 0), 2, '.', '')); ?>"></td>
                                    <td><input type="number" step="0.01" min="0" max="100" name="commission_pct" class="form-control form-control-sm text-end" value="<?php echo h(number_format((float)($it['commission_pct'] ?? 0), 2, '.', '')); ?>"></td>
                                    <td><input type="number" step="0.01" min="0" name="qty_received" class="form-control form-control-sm text-end" value="<?php echo h(number_format((float)($it['qty_received'] ?? 0), 2, '.', '')); ?>"></td>
                                    <td class="text-end"><button class="btn btn-sm btn-primary">Save</button></td>
                                </form>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="alert alert-info mt-3 small">
    <strong>Unit cost</strong> is what you owe the supplier per unit sold. <strong>Commission %</strong> is optional — the lodge's share of the sale price. The Sales Report uses these to work out each supplier's payable.
</div>

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