<?php
$pageTitle = 'Price List';
require_once __DIR__ . '/../../app/includes/header.php'; require_role_access('product:view');
require_once __DIR__ . '/../../app/includes/product_helpers.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_role_access('*');
    verify_csrf();
    $id = (int)post('product_id');
    $newPrice = (string)post('unit_price');
    if (!is_numeric($newPrice) || (float)$newPrice < 0) {
        flash('error', 'New price must be numeric and non-negative.');
        redirect('/price-list/index.php');
    }
    $stmt = db()->prepare('SELECT * FROM products WHERE id = ?');
    $stmt->execute([$id]);
    $product = $stmt->fetch();
    if (!$product) {
        flash('error', 'Product not found.');
        redirect('/price-list/index.php');
    }
    $old = (float)$product['unit_price'];
    $new = (float)$newPrice;
    $stmt = db()->prepare('UPDATE products SET unit_price = ?, updated_at = ? WHERE id = ?');
    $stmt->execute([$new, now(), $id]);
    log_activity('product_price_updated', 'Price updated for ' . $product['product_name'] . ' from ' . $old . ' to ' . $new . '.');
    flash('success', 'Product price updated successfully.');
    redirect('/price-list/index.php?' . http_build_query($_GET));
}

$products = fetch_filtered_products($_GET);
$brands = db()->query("SELECT DISTINCT brand FROM products WHERE brand IS NOT NULL AND brand <> '' ORDER BY brand")->fetchAll(PDO::FETCH_COLUMN);
?>
<div class="page-head">
    <div><h1>Price List</h1><p>Quickly update product prices used in new quotations.</p></div>
    <?php if (can_export_products()): ?><a class="btn btn-dark" href="<?= APP_BASE ?>/products/export.php"><i class="bi bi-download me-1"></i>Export Price List CSV</a><?php endif; ?>
</div>

<form class="card app-card p-3 mb-4" method="get">
    <div class="row g-3 align-items-end">
        <div class="col-md-4"><label class="form-label">Search</label><input class="form-control" name="search" value="<?= e($_GET['search'] ?? '') ?>" placeholder="Product name, brand, model"></div>
        <div class="col-md-3"><label class="form-label">Category</label><select class="form-select" name="category"><option value="">All categories</option><?php foreach (PRODUCT_CATEGORIES as $cat): ?><option value="<?= e($cat) ?>" <?= ($_GET['category'] ?? '')===$cat?'selected':'' ?>><?= e($cat) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><label class="form-label">Brand</label><select class="form-select" name="brand"><option value="">All brands</option><?php foreach ($brands as $brand): ?><option value="<?= e($brand) ?>" <?= ($_GET['brand'] ?? '')===$brand?'selected':'' ?>><?= e($brand) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><label class="form-label">Status</label><select class="form-select" name="status"><option value="">All status</option><?php foreach (PRODUCT_STATUSES as $status): ?><option value="<?= e($status) ?>" <?= ($_GET['status'] ?? '')===$status?'selected':'' ?>><?= e(ucfirst($status)) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-1 d-flex gap-2"><button class="btn btn-primary" type="submit">Apply</button><a class="btn btn-outline-secondary" href="<?= APP_BASE ?>/price-list/index.php">Reset</a></div>
    </div>
</form>

<div class="card app-card"><div class="table-responsive"><table class="table align-middle mb-0">
<thead><tr><th>SL</th><th>Product Category</th><th>Product Name</th><th>Brand</th><th>Model</th><th>Current Unit Price</th><th>New Unit Price</th><th>Status</th><th>Save</th></tr></thead><tbody>
<?php foreach ($products as $i => $p): $formId = 'price-form-' . (int)$p['id']; ?><tr>
    <td><?= $i + 1 ?></td><td><?= e($p['product_category']) ?></td><td><?= e($p['product_name']) ?></td><td><?= e($p['brand']) ?></td><td><?= e($p['model']) ?></td><td><?= money((float)$p['unit_price']) ?></td>
    <td><form id="<?= e($formId) ?>" method="post"><?= csrf_field() ?><input type="hidden" name="product_id" value="<?= (int)$p['id'] ?>"></form><input form="<?= e($formId) ?>" class="form-control form-control-sm" type="number" min="0" step="0.01" name="unit_price" value="<?= e((string)$p['unit_price']) ?>" <?= can_manage_products()?'':'disabled' ?>></td>
    <td><span class="badge text-bg-<?= $p['status']==='active'?'success':'secondary' ?>"><?= e(ucfirst($p['status'])) ?></span></td>
    <td><?php if (can_manage_products()): ?><button form="<?= e($formId) ?>" class="btn btn-sm btn-primary" type="submit">Save</button><?php else: ?><span class="text-muted small">View only</span><?php endif; ?></td>
</tr><?php endforeach; ?>
<?php if (!$products): ?><tr><td colspan="9" class="text-center text-muted py-4">No products found.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php require_once __DIR__ . '/../../app/includes/footer.php'; ?>
