<?php
session_start();
require_once __DIR__ . '/../includes/lang.php';
require_once __DIR__ . '/../includes/auth.php';
require_role('admin');
require_once __DIR__ . '/../includes/helpers.php';
$pdo = db();

$message = '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['client_id'], $_POST['product_id'])) {
    $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) {
        // Upsert logic
        $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) {
            $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 {
            $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("
    SELECT
        cp.client_id,
        cp.product_id,
        cp.price_net,
        cp.price_gross,
        c.name as client_name,
        p.name as product_name
    FROM client_prices cp
    JOIN clients c ON cp.client_id = c.id
    JOIN products p ON cp.product_id = p.id
    ORDER BY c.name, p.name
");
$existingPrices = $pricesStmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cennik indywidualny</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/custom.css">
</head>
<body>
    <?php include 'menu.php'; ?>

    <div class="container mt-4">
        <div class="card">
            <div class="card-header">
                <h2>Cennik indywidualny</h2>
            </div>
            <div class="card-body">
                <?php if ($message) echo $message; ?>

                <div class="card mb-4">
                    <div class="card-header">
                        <h3>Dodaj/Edytuj cenę</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="client_prices.php">
                            <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">Zapisz</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>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($existingPrices)): ?>
                                <tr>
                                    <td colspan="4" class="text-center">Brak zdefiniowanych cen indywidualnych.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($existingPrices as $price): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($price['client_name']); ?></td>
                                        <td><?php echo htmlspecialchars($price['product_name']); ?></td>
                                        <td><?php echo number_format($price['price_net'], 2, ',', ' '); ?></td>
                                        <td><?php echo number_format($price['price_gross'], 2, ',', ' '); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const priceNetInput = document.getElementById('price_net');
            const priceGrossInput = document.getElementById('price_gross');
            const vatRate = 1.23;

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

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

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