<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/barcode_utils.php';

require_login();
$user = current_user();

$errors = [];
$success = null;

// -------- Helpers ----------
function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }

function product_exists_by_barcode(mysqli $conn, string $barcode, ?int $excludeId = null): bool {
    $sql = "SELECT id FROM products WHERE barcode_value = ? " . ($excludeId ? "AND id <> ?" : "") . " LIMIT 1";
    $stmt = $conn->prepare($sql);
    if ($excludeId) $stmt->bind_param("si", $barcode, $excludeId);
    else $stmt->bind_param("s", $barcode);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res && $res->num_rows > 0;
}

function product_exists_by_sku(mysqli $conn, string $sku, ?int $excludeId = null): bool {
    $sql = "SELECT id FROM products WHERE sku = ? " . ($excludeId ? "AND id <> ?" : "") . " LIMIT 1";
    $stmt = $conn->prepare($sql);
    if ($excludeId) $stmt->bind_param("si", $sku, $excludeId);
    else $stmt->bind_param("s", $sku);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res && $res->num_rows > 0;
}

// -------- Add / Edit / Delete ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $category_id = (int)($_POST['category_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $unit_price = (float)($_POST['unit_price'] ?? 0);
        $reorder_level = (int)($_POST['reorder_level'] ?? 0);

        // Optional barcode input (if user wants to set it manually)
        $barcode_value = digits_only(trim($_POST['barcode_value'] ?? ''));

        if ($name === '') $errors[] = "Product name is required.";
        if ($sku === '') $errors[] = "SKU is required.";

        if ($sku !== '' && product_exists_by_sku($conn, $sku, null)) {
            $errors[] = "SKU already exists.";
        }

        if ($barcode_value !== '') {
            if (strlen($barcode_value) !== 12 || !is_valid_upc_a($barcode_value)) {
                $errors[] = "Barcode must be a valid 12-digit UPC-A (with correct check digit). Leave blank to auto-generate.";
            } else if (product_exists_by_barcode($conn, $barcode_value, null)) {
                $errors[] = "Barcode already exists.";
            }
        }

        if (!$errors) {
            // Insert first (so we have product id) then generate barcode if empty
            $stmt = $conn->prepare("INSERT INTO products (name, sku, category_id, description, unit_price, reorder_level, barcode_value)
                                    VALUES (?, ?, ?, ?, ?, ?, NULL)");
            $stmt->bind_param("ssisd i", $name, $sku, $category_id, $description, $unit_price, $reorder_level);
            // The bind_param above has a spacing issue with types in some PHP versions; fix by binding correctly:
        }
    }

    // The above had a bind_param typo due to older copies; we will handle using a safer branch below:
    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $category_id = (int)($_POST['category_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $unit_price = (float)($_POST['unit_price'] ?? 0);
        $reorder_level = (int)($_POST['reorder_level'] ?? 0);
        $barcode_value = digits_only(trim($_POST['barcode_value'] ?? ''));

        if ($name === '') $errors[] = "Product name is required.";
        if ($sku === '') $errors[] = "SKU is required.";

        if ($sku !== '' && product_exists_by_sku($conn, $sku, null)) {
            $errors[] = "SKU already exists.";
        }

        if ($barcode_value !== '') {
            if (strlen($barcode_value) !== 12 || !is_valid_upc_a($barcode_value)) {
                $errors[] = "Barcode must be a valid 12-digit UPC-A (with correct check digit). Leave blank to auto-generate.";
            } else if (product_exists_by_barcode($conn, $barcode_value, null)) {
                $errors[] = "Barcode already exists.";
            }
        }

        if (!$errors) {
            // Insert product without barcode first.
            $stmt = $conn->prepare("INSERT INTO products (name, sku, category_id, description, unit_price, reorder_level, barcode_value)
                                    VALUES (?, ?, ?, ?, ?, ?, NULL)");
            $stmt->bind_param("ssisdi", $name, $sku, $category_id, $description, $unit_price, $reorder_level);
            if (!$stmt->execute()) {
                $errors[] = "Failed to add product: " . $stmt->error;
            } else {
                $newId = (int)$stmt->insert_id;

                // If barcode not provided, generate based on product id.
                if ($barcode_value === '') {
                    $barcode_value = generate_upc_a_from_product_id($newId, '200');

                    // Ensure uniqueness (very unlikely collisions, but we check)
                    $tries = 0;
                    while (product_exists_by_barcode($conn, $barcode_value, null) && $tries < 10) {
                        $tries++;
                        // tweak prefix slightly
                        $barcode_value = generate_upc_a_from_product_id($newId + $tries, '200');
                    }
                }

                // Update barcode (either provided or generated)
                $stmt2 = $conn->prepare("UPDATE products SET barcode_value = ? WHERE id = ?");
                $stmt2->bind_param("si", $barcode_value, $newId);
                if (!$stmt2->execute()) {
                    $errors[] = "Product added but failed to set barcode: " . $stmt2->error;
                } else {
                    $success = "Product added successfully. Barcode: " . h($barcode_value);
                }
            }
        }
    }

    if ($action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $sku = trim($_POST['sku'] ?? '');
        $category_id = (int)($_POST['category_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $unit_price = (float)($_POST['unit_price'] ?? 0);
        $reorder_level = (int)($_POST['reorder_level'] ?? 0);
        $barcode_value = digits_only(trim($_POST['barcode_value'] ?? ''));

        if ($id <= 0) $errors[] = "Invalid product ID.";
        if ($name === '') $errors[] = "Product name is required.";
        if ($sku === '') $errors[] = "SKU is required.";

        if ($sku !== '' && product_exists_by_sku($conn, $sku, $id)) {
            $errors[] = "SKU already exists.";
        }

        if ($barcode_value === '') {
            $errors[] = "Barcode is required (12-digit UPC-A).";
        } else {
            if (strlen($barcode_value) !== 12 || !is_valid_upc_a($barcode_value)) {
                $errors[] = "Barcode must be a valid 12-digit UPC-A (with correct check digit).";
            } else if (product_exists_by_barcode($conn, $barcode_value, $id)) {
                $errors[] = "Barcode already exists.";
            }
        }

        if (!$errors) {
            $stmt = $conn->prepare("UPDATE products
                                    SET name=?, sku=?, category_id=?, description=?, unit_price=?, reorder_level=?, barcode_value=?
                                    WHERE id=?");
            $stmt->bind_param("ssisdisi", $name, $sku, $category_id, $description, $unit_price, $reorder_level, $barcode_value, $id);
            if (!$stmt->execute()) {
                $errors[] = "Failed to update product: " . $stmt->error;
            } else {
                $success = "Product updated successfully.";
            }
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) $errors[] = "Invalid product ID.";
        if (!$errors) {
            $stmt = $conn->prepare("DELETE FROM products WHERE id=?");
            $stmt->bind_param("i", $id);
            if (!$stmt->execute()) {
                $errors[] = "Failed to delete product: " . $stmt->error;
            } else {
                $success = "Product deleted successfully.";
            }
        }
    }
}

// -------- Fetch data for display ----------
$categories = [];
$res = $conn->query("SELECT id, name FROM product_categories ORDER BY name ASC");
if ($res) {
    while ($row = $res->fetch_assoc()) $categories[] = $row;
}

$products = [];
$res = $conn->query("
    SELECT p.*, c.name AS category_name
    FROM products p
    LEFT JOIN product_categories c ON c.id = p.category_id
    ORDER BY p.id DESC
");
if ($res) {
    while ($row = $res->fetch_assoc()) $products[] = $row;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Products</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .msg { padding: 10px; margin: 10px 0; border-radius: 6px; }
        .msg.error { background: #ffe9e9; border: 1px solid #ffb3b3; }
        .msg.success { background: #e9ffe9; border: 1px solid #b3ffb3; }
        .flex { display:flex; gap:12px; flex-wrap:wrap; }
        .card { background:#fff; border:1px solid #ddd; padding:12px; border-radius:8px; }
        .table { width:100%; border-collapse:collapse; }
        .table th, .table td { border:1px solid #ddd; padding:8px; }
        .table th { background:#f6f6f6; }
        .small { font-size:12px; color:#666; }
        input[type="text"], input[type="number"], textarea, select { width:100%; padding:8px; }
        .btn { padding:8px 12px; cursor:pointer; border:1px solid #333; background:#eee; }
        .btn.primary { background:#333; color:#fff; }
        .btn.danger { background:#c0392b; color:#fff; border-color:#c0392b; }
        .btn.secondary { background:#3498db; color:#fff; border-color:#3498db; }
        .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
    </style>
</head>
<body>

<?php include __DIR__ . '/partials/header.php'; ?>

<div class="container">

    <h1>Products</h1>

    <?php if ($errors): ?>
        <div class="msg error">
            <ul>
                <?php foreach ($errors as $e): ?>
                    <li><?= h($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="msg success"><?= h($success) ?></div>
    <?php endif; ?>

    <div class="flex">
        <div class="card" style="flex:1; min-width:320px;">
            <h2>Add Product</h2>
            <form method="post">
                <input type="hidden" name="action" value="add">

                <label>Name</label>
                <input type="text" name="name" required>

                <label>SKU</label>
                <input type="text" name="sku" required>

                <label>Category</label>
                <select name="category_id">
                    <option value="0">-- None --</option>
                    <?php foreach ($categories as $c): ?>
                        <option value="<?= (int)$c['id'] ?>"><?= h($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <label>Description</label>
                <textarea name="description" rows="3"></textarea>

                <label>Unit Price</label>
                <input type="number" name="unit_price" step="0.01" value="0">

                <label>Reorder Level</label>
                <input type="number" name="reorder_level" value="0">

                <label>Barcode (UPC-A 12 digits) <span class="small">leave blank to auto-generate</span></label>
                <input type="text" name="barcode_value" inputmode="numeric" pattern="[0-9]*">

                <div style="margin-top:12px;">
                    <button class="btn primary" type="submit">Add</button>
                </div>
            </form>
        </div>

        <div class="card" style="flex:2; min-width:520px;">
            <h2>Product List</h2>
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>SKU</th>
                        <th>Barcode</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Reorder</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($products as $p): ?>
                    <tr>
                        <td><?= (int)$p['id'] ?></td>
                        <td><?= h($p['name']) ?></td>
                        <td class="mono"><?= h($p['sku']) ?></td>
                        <td class="mono"><?= h($p['barcode_value']) ?></td>
                        <td><?= h($p['category_name']) ?></td>
                        <td><?= number_format((float)$p['unit_price'], 2) ?></td>
                        <td><?= (int)$p['reorder_level'] ?></td>
                        <td>
                            <button class="btn secondary" type="button"
                                    onclick="openEdit(
                                        <?= (int)$p['id'] ?>,
                                        '<?= h($p['name']) ?>',
                                        '<?= h($p['sku']) ?>',
                                        <?= (int)$p['category_id'] ?>,
                                        '<?= h($p['description']) ?>',
                                        '<?= h($p['unit_price']) ?>',
                                        <?= (int)$p['reorder_level'] ?>,
                                        '<?= h($p['barcode_value']) ?>'
                                    )">Edit</button>

                            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this product?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button class="btn danger" type="submit">Delete</button>
                            </form>

                            <a class="btn" target="_blank"
                               href="print_label.php?id=<?= (int)$p['id'] ?>&mode=both">
                                Print Label
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <div class="small" style="margin-top:10px;">
                Tip: For scanner workflows, use Stock IN / Stock OUT / Adjust pages and scan the barcode (scanner types digits + Enter).
            </div>
        </div>
    </div>

</div>

<!-- Edit Modal -->
<div id="editModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5);">
  <div style="background:#fff; max-width:720px; margin:6vh auto; padding:16px; border-radius:10px;">
    <h2>Edit Product</h2>
    <form method="post">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" id="edit_id">

        <label>Name</label>
        <input type="text" name="name" id="edit_name" required>

        <label>SKU</label>
        <input type="text" name="sku" id="edit_sku" required>

        <label>Category</label>
        <select name="category_id" id="edit_category_id">
            <option value="0">-- None --</option>
            <?php foreach ($categories as $c): ?>
                <option value="<?= (int)$c['id'] ?>"><?= h($c['name']) ?></option>
            <?php endforeach; ?>
        </select>

        <label>Description</label>
        <textarea name="description" id="edit_description" rows="3"></textarea>

        <label>Unit Price</label>
        <input type="number" name="unit_price" step="0.01" id="edit_unit_price" value="0">

        <label>Reorder Level</label>
        <input type="number" name="reorder_level" id="edit_reorder_level" value="0">

        <label>Barcode (UPC-A 12 digits)</label>
        <input type="text" name="barcode_value" id="edit_barcode_value" inputmode="numeric" pattern="[0-9]*" required>

        <div style="margin-top:12px;">
            <button class="btn primary" type="submit">Save</button>
            <button class="btn" type="button" onclick="closeEdit()">Cancel</button>
        </div>
    </form>
  </div>
</div>

<script>
function openEdit(id, name, sku, categoryId, description, unitPrice, reorderLevel, barcodeValue) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_sku').value = sku;
    document.getElementById('edit_category_id').value = categoryId;
    document.getElementById('edit_description').value = description;
    document.getElementById('edit_unit_price').value = unitPrice;
    document.getElementById('edit_reorder_level').value = reorderLevel;
    document.getElementById('edit_barcode_value').value = barcodeValue;

    document.getElementById('editModal').style.display = 'block';
}
function closeEdit() {
    document.getElementById('editModal').style.display = 'none';
}
</script>

</body>
</html>