<?php
require_once __DIR__ . '/../includes/init.php';
require_role('admin');
$pdo = db();

$message = '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['client_id'], $_POST['product_id'])) {
    $action = $_POST['form_action'] ?? 'add';

    $clientId = $_POST['client_id'];
    $productId = $_POST['product_id'];
    $priceNet = isset($_POST['price_net']) && is_numeric($_POST['price_net']) ? (float)$_POST['price_net'] : null;
    $priceGross = isset($_POST['price_gross']) && is_numeric($_POST['price_gross']) ? (float)$_POST['price_gross'] : null;

    // Server-side validation and calculation
    if ($priceGross !== null) {
        $priceNet = round($priceGross / 1.23, 2);
    } elseif ($priceNet !== null) {
        $priceGross = round($priceNet * 1.23, 2);
    }

    if (!empty($clientId) && !empty($productId) && $priceNet !== null && $priceGross !== null) {
        if ($action === 'update') {
            $stmt = $pdo->prepare("UPDATE client_prices SET price_net = :price_net, price_gross = :price_gross WHERE client_id = :client_id AND product_id = :product_id");
            $stmt->execute(['price_net' => $priceNet, 'price_gross' => $priceGross, 'client_id' => $clientId, 'product_id' => $productId]);
            $message = '<div class="alert alert-success">Cena została zaktualizowana.</div>';
        } else { // 'add' action
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM client_prices WHERE client_id = :client_id AND product_id = :product_id");
            $stmt->execute(['client_id' => $clientId, 'product_id' => $productId]);
            $exists = $stmt->fetchColumn() > 0;

            if ($exists) {
                $message = '<div class="alert alert-danger">Cena dla tego klienta i produktu już istnieje. Użyj opcji edycji w tabeli poniżej.</div>';
            } else {
                $stmt = $pdo->prepare("INSERT INTO client_prices (client_id, product_id, price_net, price_gross) VALUES (:client_id, :product_id, :price_net, :price_gross)");
                $stmt->execute(['client_id' => $clientId, 'product_id' => $productId, 'price_net' => $priceNet, 'price_gross' => $priceGross]);
                $message = '<div class="alert alert-success">Nowa cena została dodana.</div>';
            }
        }
    } else {
        $message = '<div class="alert alert-danger">Wszystkie pola są wymagane, a ceny muszą być prawidłowymi liczbami.</div>';
    }
}

// Fetch data for display
$clients = $pdo->query("SELECT id, name FROM clients ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$products = $pdo->query("SELECT id, name FROM products ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

// Fetch existing prices
$pricesStmt = $pdo->query("\n    SELECT\n        cp.client_id,\n        cp.product_id,\n        cp.price_net,\n        cp.price_gross,\n        c.name as client_name,\n        p.name as product_name\n    FROM client_prices cp\n    JOIN clients c ON cp.client_id = c.id\n    JOIN products p ON cp.product_id = p.id\n    ORDER BY c.name, p.name\n");
$existingPrices = $pricesStmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = "Cennik indywidualny";
?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<body>
    <?php include 'menu.php'; ?>

    <main class="container my-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h2"><?php echo $page_title; ?></h1>
        </div>

        <div class="card">
            <div class="card-body">
                <?php if ($message) echo $message; ?>

                <div class="card mb-4">
                    <div class="card-header">
                        <h3>Dodaj nową cenę</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="client_prices.php">
                            <input type="hidden" name="form_action" value="add">
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label for="client_id" class="form-label">Klient:</label>
                                    <select name="client_id" id="client_id" class="form-select" required>
                                        <option value="">Wybierz klienta</option>
                                        <?php foreach ($clients as $client): ?>
                                            <option value="<?php echo $client['id']; ?>"><?php echo htmlspecialchars($client['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label for="product_id" class="form-label">Produkt:</label>
                                    <select name="product_id" id="product_id" class="form-select" required>
                                        <option value="">Wybierz produkt</option>
                                        <?php foreach ($products as $product): ?>
                                            <option value="<?php echo $product['id']; ?>"><?php echo htmlspecialchars($product['name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="price_net" class="form-label">Cena netto (PLN):</label>
                                    <input type="number" step="0.01" name="price_net" id="price_net" class="form-control">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="price_gross" class="form-label">Cena brutto (PLN):</label>
                                    <input type="number" step="0.01" name="price_gross" id="price_gross" class="form-control">
                                </div>
                                <div class="col-md-2 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary w-100">Dodaj</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <h3>Istniejące ceny indywidualne</h3>
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Klient</th>
                                <th>Produkt</th>
                                <th>Cena netto (PLN)</th>
                                <th>Cena brutto (PLN)</th>
                                <th>Akcje</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($existingPrices)): ?>
                                <tr>
                                    <td colspan="5" class="text-center">Brak zdefiniowanych cen indywidualnych.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($existingPrices as $price): ?>
                                    <tr 
                                        id="row-<?php echo $price['client_id']; ?>-<?php echo $price['product_id']; ?>"
                                        data-client-id="<?php echo $price['client_id']; ?>"
                                        data-product-id="<?php echo $price['product_id']; ?>"
                                        data-price-net="<?php echo $price['price_net']; ?>"
                                        data-price-gross="<?php echo $price['price_gross']; ?>"
                                    >
                                        <td><?php echo htmlspecialchars($price['client_name']); ?></td>
                                        <td><?php echo htmlspecialchars($price['product_name']); ?></td>
                                        <td>
                                            <span class="view-mode"><?php echo number_format($price['price_net'], 2, ',', ' '); ?></span>
                                            <input type="number" step="0.01" class="form-control edit-mode price-net-input" value="<?php echo $price['price_net']; ?>" style="display: none;">
                                        </td>
                                        <td>
                                            <span class="view-mode"><?php echo number_format($price['price_gross'], 2, ',', ' '); ?></span>
                                            <input type="number" step="0.01" class="form-control edit-mode price-gross-input" value="<?php echo $price['price_gross']; ?>" style="display: none;">
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-secondary edit-btn view-mode">Edytuj</button>
                                            <button type="button" class="btn btn-sm btn-primary save-btn edit-mode" style="display: none;">Zapisz</button>
                                            <button type="button" class="btn btn-sm btn-light cancel-btn edit-mode" style="display: none;">Anuluj</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // VAT Rate
            const vatRate = 1.23;

            // --- Script for top form ---
            const mainPriceNetInput = document.getElementById('price_net');
            const mainPriceGrossInput = document.getElementById('price_gross');

            if (mainPriceNetInput && mainPriceGrossInput) {
                mainPriceNetInput.addEventListener('input', function () {
                    const netValue = parseFloat(this.value);
                    if (!isNaN(netValue)) {
                        mainPriceGrossInput.value = (netValue * vatRate).toFixed(2);
                    } else {
                        mainPriceGrossInput.value = '';
                    }
                });

                mainPriceGrossInput.addEventListener('input', function () {
                    const grossValue = parseFloat(this.value);
                    if (!isNaN(grossValue)) {
                        mainPriceNetInput.value = (grossValue / vatRate).toFixed(2);
                    } else {
                        mainPriceNetInput.value = '';
                    }
                });
            }

            // --- Script for inline table editing ---
            const tableBody = document.querySelector('.table-responsive tbody');

            if (tableBody) {
                // Function to toggle modes
                function toggleEditMode(row, edit) {
                    const viewElements = row.querySelectorAll('.view-mode');
                    const editElements = row.querySelectorAll('.edit-mode');
                    
                    viewElements.forEach(el => el.style.display = edit ? 'none' : '');
                    editElements.forEach(el => el.style.display = edit ? '' : 'none');
                }

                // Attach event listeners
                tableBody.addEventListener('click', function(e) {
                    const target = e.target;
                    const row = target.closest('tr');

                    if (target.classList.contains('edit-btn')) {
                        toggleEditMode(row, true);
                    }

                    if (target.classList.contains('cancel-btn')) {
                        // Reset values before hiding
                        const originalNet = row.dataset.priceNet;
                        const originalGross = row.dataset.priceGross;
                        row.querySelector('.price-net-input').value = originalNet;
                        row.querySelector('.price-gross-input').value = originalGross;
                        toggleEditMode(row, false);
                    }

                    if (target.classList.contains('save-btn')) {
                        const clientId = row.dataset.clientId;
                        const productId = row.dataset.productId;
                        const priceNet = row.querySelector('.price-net-input').value;
                        const priceGross = row.querySelector('.price-gross-input').value;

                        // Create and submit a dynamic form
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = 'client_prices.php';
                        
                        const fields = {
                            client_id: clientId,
                            product_id: productId,
                            price_net: priceNet,
                            price_gross: priceGross,
                            form_action: 'update'
                        };

                        for (const key in fields) {
                            const input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = key;
                            input.value = fields[key];
                            form.appendChild(input);
                        }

                        document.body.appendChild(form);
                        form.submit();
                    }
                });

                // Add live calculation for inline inputs
                tableBody.addEventListener('input', function(e) {
                    const target = e.target;
                    const row = target.closest('tr');
                    if (!row) return;

                    const priceNetInput = row.querySelector('.price-net-input');
                    const priceGrossInput = row.querySelector('.price-gross-input');
                    
                    if (target === priceNetInput) {
                        const netValue = parseFloat(target.value);
                        if (!isNaN(netValue)) {
                            priceGrossInput.value = (netValue * vatRate).toFixed(2);
                        } else {
                            priceGrossInput.value = '';
                        }
                    }

                    if (target === priceGrossInput) {
                        const grossValue = parseFloat(target.value);
                        if (!isNaN(grossValue)) {
                            priceNetInput.value = (grossValue / vatRate).toFixed(2);
                        } else {
                            priceNetInput.value = '';
                        }
                    }
                });
            }
        });
    </script>

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