<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$products = $pdo->query('SELECT id, name, price, stock FROM products WHERE is_active = 1 ORDER BY name')->fetchAll();

$errors = [];
$values = [
    'sold_at' => date('Y-m-d\TH:i'),
    'customer_name' => '',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['sold_at'] = trim($_POST['sold_at'] ?? '');
    $values['customer_name'] = trim($_POST['customer_name'] ?? '');

    $productIds = $_POST['product_id'] ?? [];
    $qtys = $_POST['qty'] ?? [];
    $prices = $_POST['price'] ?? [];

    if ($values['sold_at'] === '' || !strtotime($values['sold_at'])) {
        $errors['sold_at'] = 'Tanggal transaksi tidak valid.';
    }

    $items = [];
    $total = 0;

    foreach ($productIds as $index => $productIdRaw) {
        $productId = (int) $productIdRaw;
        $qty = (int) ($qtys[$index] ?? 0);
        $price = (float) ($prices[$index] ?? 0);

        if ($productId <= 0 || $qty <= 0) {
            continue;
        }

        $items[] = [
            'product_id' => $productId,
            'qty' => $qty,
            'price' => $price,
        ];
    }

    if (!$items) {
        $errors['items'] = 'Tambahkan minimal 1 item.';
    }

    if (!$errors) {
        $pdo->beginTransaction();
        try {
            $code = 'OFF' . date('YmdHis') . rand(100, 999);
            $soldAt = date('Y-m-d H:i:s', strtotime($values['sold_at']));

            $saleStmt = $pdo->prepare('INSERT INTO offline_sales (code, sold_at, cashier_id, customer_name, subtotal, total, note) VALUES (?, ?, ?, ?, ?, ?, ?)');
            $itemStmt = $pdo->prepare('INSERT INTO offline_sale_items (offline_sale_id, product_id, qty, price, subtotal) VALUES (?, ?, ?, ?, ?)');
            $stockStmt = $pdo->prepare('UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?');

            $subtotal = 0;
            foreach ($items as $item) {
                $subtotal += $item['price'] * $item['qty'];
            }

            $saleStmt->execute([
                $code,
                $soldAt,
                current_user()['id'],
                $values['customer_name'] ?: null,
                $subtotal,
                $subtotal,
                null,
            ]);
            $saleId = (int) $pdo->lastInsertId();

            foreach ($items as $item) {
                $lineSubtotal = $item['price'] * $item['qty'];
                $itemStmt->execute([$saleId, $item['product_id'], $item['qty'], $item['price'], $lineSubtotal]);

                $stockStmt->execute([$item['qty'], $item['product_id'], $item['qty']]);
                if ($stockStmt->rowCount() === 0) {
                    throw new RuntimeException('Stok tidak mencukupi untuk produk ID ' . $item['product_id']);
                }
            }

            $pdo->commit();
            flash_message('success', 'Transaksi offline berhasil disimpan.');
            redirect(base_url('admin/sales_offline.php'));
        } catch (Throwable $e) {
            $pdo->rollBack();
            flash_message('error', 'Gagal menyimpan transaksi: ' . $e->getMessage());
            redirect(base_url('admin/sales_offline_add.php'));
        }
    }
}
?>

<h2 class="fw-bold mb-4">Tambah Penjualan Offline</h2>

<div class="card shadow-sm">
    <div class="card-body">
        <?php if (!empty($errors['items'])): ?>
            <div class="alert error"><?= sanitize($errors['items']); ?></div>
        <?php endif; ?>
        <form method="post">
            <div class="row g-3">
                <div class="col-md-4">
                    <label>Tanggal Transaksi</label>
                    <input class="form-control" type="datetime-local" name="sold_at" value="<?= sanitize($values['sold_at']); ?>" required>
                    <?php if (!empty($errors['sold_at'])): ?><small class="error"><?= sanitize($errors['sold_at']); ?></small><?php endif; ?>
                </div>
                <div class="col-md-4">
                    <label>Nama Pembeli (opsional)</label>
                    <input class="form-control" type="text" name="customer_name" value="<?= sanitize($values['customer_name']); ?>">
                </div>
            </div>

            <h5 class="fw-bold mt-4">Item Produk</h5>
            <div class="table-responsive">
                <table class="table align-middle" id="itemsTable">
                    <thead>
                        <tr>
                            <th>Produk</th>
                            <th>Stok</th>
                            <th>Harga</th>
                            <th>Qty</th>
                            <th>Subtotal</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <select class="form-select product-select" name="product_id[]" required>
                                    <option value="">Pilih produk</option>
                                    <?php foreach ($products as $product): ?>
                                        <option value="<?= (int) $product['id']; ?>" data-price="<?= (float) $product['price']; ?>" data-stock="<?= (int) $product['stock']; ?>">
                                            <?= sanitize($product['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td class="stock-cell">-</td>
                            <td><input class="form-control price-input" type="number" name="price[]" min="0" step="1000" required></td>
                            <td><input class="form-control qty-input" type="number" name="qty[]" min="1" value="1" required></td>
                            <td class="subtotal-cell">0</td>
                            <td><button class="btn btn-sm remove-row" type="button">Hapus</button></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <button class="btn btn-sm" type="button" id="addRow">Tambah Item</button>

            <div class="d-flex justify-content-end mt-3">
                <div class="card p-3" style="min-width: 260px;">
                    <div class="d-flex justify-content-between">
                        <span>Total</span>
                        <strong id="totalValue">0</strong>
                    </div>
                </div>
            </div>

            <button class="btn mt-3" type="submit">Simpan Transaksi</button>
        </form>
    </div>
</div>

<script>
const table = document.getElementById('itemsTable');
const totalValue = document.getElementById('totalValue');

document.getElementById('addRow').addEventListener('click', () => {
    const row = table.tBodies[0].rows[0].cloneNode(true);
    row.querySelectorAll('input').forEach((input) => {
        input.value = '';
    });
    row.querySelector('.stock-cell').textContent = '-';
    row.querySelector('.subtotal-cell').textContent = '0';
    row.querySelector('.product-select').selectedIndex = 0;
    table.tBodies[0].appendChild(row);
});

table.addEventListener('change', (event) => {
    if (event.target.classList.contains('product-select')) {
        const option = event.target.selectedOptions[0];
        const row = event.target.closest('tr');
        row.querySelector('.price-input').value = option.dataset.price || '';
        row.querySelector('.stock-cell').textContent = option.dataset.stock || '-';
    }
    recalc();
});

table.addEventListener('input', (event) => {
    if (event.target.classList.contains('qty-input') || event.target.classList.contains('price-input')) {
        recalc();
    }
});

table.addEventListener('click', (event) => {
    if (event.target.classList.contains('remove-row')) {
        const rows = table.tBodies[0].rows;
        if (rows.length > 1) {
            event.target.closest('tr').remove();
            recalc();
        }
    }
});

function recalc() {
    let total = 0;
    [...table.tBodies[0].rows].forEach((row) => {
        const qty = parseFloat(row.querySelector('.qty-input').value || 0);
        const price = parseFloat(row.querySelector('.price-input').value || 0);
        const subtotal = qty * price;
        row.querySelector('.subtotal-cell').textContent = subtotal.toLocaleString('id-ID');
        total += subtotal;
    });
    totalValue.textContent = total.toLocaleString('id-ID');
}
</script>

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