<?php
require_once 'config.php';

// Get products for dropdown
$products = $pdo->query("SELECT * FROM products ORDER BY name")->fetchAll();

// Get clients for dropdown
$clients = $pdo->query("SELECT * FROM clients ORDER BY name")->fetchAll();

// Get invoice data if editing
$invoice = null;
$invoice_items = [];
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM invoices WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $invoice = $stmt->fetch();
    
    if ($invoice) {
        $stmt = $pdo->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
        $stmt->execute([$invoice['id']]);
        $invoice_items = $stmt->fetchAll();
    }
}

// Handle new client via AJAX
if (isset($_POST['action']) && $_POST['action'] == 'add_client') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    
    $stmt = $pdo->prepare("INSERT INTO clients (name, email, phone, address) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $email, $phone, $address]);
    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name]);
    exit;
}

// Handle new product via AJAX
if (isset($_POST['action']) && $_POST['action'] == 'add_product') {
    $name = $_POST['name'];
    $price = $_POST['price'];
    $vat_rate = $_POST['vat_rate'] ?? 20;
    $description = $_POST['description'] ?? '';
    
    $stmt = $pdo->prepare("INSERT INTO products (name, description, price, vat_rate) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $description, $price, $vat_rate]);
    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name, 'price' => $price, 'vat_rate' => $vat_rate]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="sq">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Faturimi - Gjenerimi i Faturave</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body { background: #f8f9fa; }
        .invoice-container { max-width: 1200px; margin: 30px auto; }
        .card { border: none; box-shadow: 0 0 20px rgba(0,0,0,0.08); border-radius: 15px; }
        .card-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px 15px 0 0 !important; padding: 20px 25px; }
        .form-label { font-weight: 600; color: #333; }
        .item-row { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 10px; }
        .item-row .form-control { background: white; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); }
        .btn-success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); border: none; }
        .btn-success:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(17, 153, 142, 0.4); }
        .logo-preview { max-width: 150px; max-height: 60px; object-fit: contain; }
        .remove-item { cursor: pointer; color: #dc3545; }
        .remove-item:hover { color: #a71d2a; }
        .total-display { background: #f0f0f0; padding: 20px; border-radius: 10px; margin-top: 15px; }
        .total-display .row { margin: 0; padding: 5px 0; }
        .total-display .total-final { font-size: 24px; font-weight: bold; color: #667eea; }
        .modal-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-close-white { filter: invert(1); }
        .add-btn { cursor: pointer; color: #667eea; }
        .add-btn:hover { color: #764ba2; }
    </style>
</head>
<body>
    <div class="container invoice-container">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="bi bi-file-earmark-text me-2"></i>Gjenerimi i Faturës</h4>
                <div>
                    <a href="?new" class="btn btn-light btn-sm"><i class="bi bi-plus-circle"></i> Faturë e Re</a>
                    <a href="#" onclick="window.location.reload();" class="btn btn-light btn-sm"><i class="bi bi-arrow-clockwise"></i> Rifresko</a>
                </div>
            </div>
            <div class="card-body p-4">
                <form id="invoiceForm" action="generate_invoice.php" method="POST" target="_blank">
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="text-center">
                                <img src="<?php echo COMPANY_LOGO; ?>" alt="Logo" class="logo-preview" id="logoPreview" onerror="this.style.display='none'">
                                <p class="text-muted small mt-1"><i class="bi bi-info-circle"></i> Logo default</p>
                            </div>
                        </div>
                        <div class="col-md-9">
                            <div class="row">
                                <div class="col-md-6">
                                    <h5 class="text-primary"><?php echo COMPANY_NAME; ?></h5>
                                    <p class="text-muted small mb-1"><?php echo COMPANY_ADDRESS; ?></p>
                                    <p class="text-muted small mb-1">Tel: <?php echo COMPANY_PHONE; ?></p>
                                    <p class="text-muted small">Email: <?php echo COMPANY_EMAIL; ?></p>
                                </div>
                                <div class="col-md-6 text-md-end">
                                    <div class="mb-2">
                                        <label class="form-label small">Nr. Faturës:</label>
                                        <input type="text" name="invoice_number" class="form-control form-control-sm" value="<?php echo generateInvoiceNumber(); ?>" readonly>
                                    </div>
                                    <div>
                                        <label class="form-label small">Data:</label>
                                        <input type="date" name="invoice_date" class="form-control form-control-sm" value="<?php echo date('Y-m-d'); ?>" required>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Klienti <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <select name="client_id" class="form-select" id="clientSelect" required>
                                    <option value="">Zgjedh klientin...</option>
                                    <?php foreach($clients as $client): ?>
                                    <option value="<?php echo $client['id']; ?>" <?php echo ($invoice && $invoice['client_id'] == $client['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($client['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addClientModal">
                                    <i class="bi bi-plus-circle"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Data e pagesës</label>
                            <input type="date" name="due_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                        </div>
                    </div>

                    <hr>

                    <div class="mb-3">
                        <h5><i class="bi bi-cart me-2"></i>Artikujt e Faturës</h5>
                        <div id="itemsContainer">
                            <?php if (empty($invoice_items)): ?>
                            <div class="item-row row g-2">
                                <div class="col-md-5">
                                    <div class="input-group">
                                        <select name="products[]" class="form-select product-select" required>
                                            <option value="">Zgjedh produktin...</option>
                                            <?php foreach($products as $product): ?>
                                            <option value="<?php echo $product['id']; ?>" data-price="<?php echo $product['price']; ?>" data-vat="<?php echo $product['vat_rate']; ?>">
                                                <?php echo htmlspecialchars($product['name']); ?> - <?php echo formatCurrency($product['price']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="button" class="btn btn-outline-primary add-product-btn" data-bs-toggle="modal" data-bs-target="#addProductModal">
                                            <i class="bi bi-plus-circle"></i>
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <input type="number" name="quantities[]" class="form-control quantity" placeholder="Sasi" min="1" value="1" required>
                                </div>
                                <div class="col-md-2">
                                    <input type="number" name="unit_prices[]" class="form-control unit-price" placeholder="Cmimi" step="0.01" required>
                                </div>
                                <div class="col-md-2">
                                    <input type="text" class="form-control item-total" readonly placeholder="Totali">
                                </div>
                                <div class="col-md-1">
                                    <i class="bi bi-trash remove-item fs-5"></i>
                                </div>
                            </div>
                            <?php else: ?>
                                <?php foreach($invoice_items as $item): ?>
                                <div class="item-row row g-2">
                                    <div class="col-md-5">
                                        <div class="input-group">
                                            <select name="products[]" class="form-select product-select" required>
                                                <option value="">Zgjedh produktin...</option>
                                                <?php foreach($products as $product): ?>
                                                <option value="<?php echo $product['id']; ?>" data-price="<?php echo $product['price']; ?>" data-vat="<?php echo $product['vat_rate']; ?>" <?php echo ($item['product_id'] == $product['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($product['name']); ?> - <?php echo formatCurrency($product['price']); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <button type="button" class="btn btn-outline-primary add-product-btn" data-bs-toggle="modal" data-bs-target="#addProductModal">
                                                <i class="bi bi-plus-circle"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="number" name="quantities[]" class="form-control quantity" placeholder="Sasi" min="1" value="<?php echo $item['quantity']; ?>" required>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="number" name="unit_prices[]" class="form-control unit-price" placeholder="Cmimi" step="0.01" value="<?php echo $item['unit_price']; ?>" required>
                                    </div>
                                    <div class="col-md-2">
                                        <input type="text" class="form-control item-total" readonly value="<?php echo formatCurrency($item['total']); ?>">
                                    </div>
                                    <div class="col-md-1">
                                        <i class="bi bi-trash remove-item fs-5"></i>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm mt-2" id="addItemBtn">
                            <i class="bi bi-plus-circle"></i> Shto Artikull
                        </button>
                    </div>

                    <div class="total-display">
                        <div class="row">
                            <div class="col-md-8"></div>
                            <div class="col-md-4">
                                <div class="row">
                                    <div class="col-6">Nëntotali:</div>
                                    <div class="col-6 text-end" id="subtotalDisplay">0.00 €</div>
                                </div>
                                <div class="row">
                                    <div class="col-6">TVSH (20%):</div>
                                    <div class="col-6 text-end" id="vatDisplay">0.00 €</div>
                                </div>
                                <hr>
                                <div class="row total-final">
                                    <div class="col-6">TOTALI:</div>
                                    <div class="col-6 text-end" id="totalDisplay">0.00 €</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <input type="hidden" name="subtotal" id="subtotalInput" value="0">
                    <input type="hidden" name="vat_total" id="vatInput" value="0">
                    <input type="hidden" name="total" id="totalInput" value="0">

                    <div class="mt-4 d-flex gap-2">
                        <button type="submit" class="btn btn-success btn-lg flex-grow-1">
                            <i class="bi bi-file-pdf me-2"></i>Gjenero Faturën (PDF)
                        </button>
                        <button type="reset" class="btn btn-secondary btn-lg">
                            <i class="bi bi-arrow-counterclockwise"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Client Modal -->
    <div class="modal fade" id="addClientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-person-plus me-2"></i>Shto Klient të Ri</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addClientForm">
                        <div class="mb-3">
                            <label class="form-label">Emri <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="clientName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" id="clientEmail">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Telefoni</label>
                            <input type="text" class="form-control" id="clientPhone">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Adresa</label>
                            <textarea class="form-control" id="clientAddress" rows="2"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulo</button>
                    <button type="button" class="btn btn-primary" id="saveClientBtn"><i class="bi bi-save me-1"></i>Ruaj Klientin</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Product Modal -->
    <div class="modal fade" id="addProductModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-box-plus me-2"></i>Shto Produkt të Ri</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addProductForm">
                        <div class="mb-3">
                            <label class="form-label">Emri i Produktit <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="productName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Përshkrimi</label>
                            <textarea class="form-control" id="productDescription" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Çmimi <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="productPrice" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">TVSH (%)</label>
                            <input type="number" class="form-control" id="productVat" value="20" step="0.01">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Anulo</button>
                    <button type="button" class="btn btn-primary" id="saveProductBtn"><i class="bi bi-save me-1"></i>Ruaj Produktin</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Calculate totals
        function calculateTotals() {
            let subtotal = 0;
            const itemRows = document.querySelectorAll('.item-row');
            
            itemRows.forEach(row => {
                const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
                const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
                const total = quantity * unitPrice;
                const totalInput = row.querySelector('.item-total');
                totalInput.value = total.toFixed(2) + ' €';
                subtotal += total;
            });

            const vatRate = 20;
            const vatTotal = subtotal * (vatRate / 100);
            const total = subtotal + vatTotal;

            document.getElementById('subtotalDisplay').textContent = subtotal.toFixed(2) + ' €';
            document.getElementById('vatDisplay').textContent = vatTotal.toFixed(2) + ' €';
            document.getElementById('totalDisplay').textContent = total.toFixed(2) + ' €';

            document.getElementById('subtotalInput').value = subtotal.toFixed(2);
            document.getElementById('vatInput').value = vatTotal.toFixed(2);
            document.getElementById('totalInput').value = total.toFixed(2);
        }

        // Add new item row
        document.getElementById('addItemBtn').addEventListener('click', function() {
            const container = document.getElementById('itemsContainer');
            const firstRow = container.querySelector('.item-row');
            const newRow = firstRow.cloneNode(true);
            
            newRow.querySelector('.product-select').value = '';
            newRow.querySelector('.quantity').value = 1;
            newRow.querySelector('.unit-price').value = '';
            newRow.querySelector('.item-total').value = '';
            
            container.appendChild(newRow);
            attachItemEvents(newRow);
            calculateTotals();
        });

        // Remove item row
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-item')) {
                const row = e.target.closest('.item-row');
                if (document.querySelectorAll('.item-row').length > 1) {
                    row.remove();
                    calculateTotals();
                } else {
                    alert('Duhet të ketë të paktën një artikull!');
                }
            }
        });

        // Attach events to a single row
        function attachItemEvents(row) {
            const productSelect = row.querySelector('.product-select');
            const quantity = row.querySelector('.quantity');
            const unitPrice = row.querySelector('.unit-price');

            productSelect.addEventListener('change', function() {
                const selected = this.options[this.selectedIndex];
                if (selected && selected.dataset.price) {
                    unitPrice.value = selected.dataset.price;
                    calculateTotals();
                }
            });

            quantity.addEventListener('input', calculateTotals);
            unitPrice.addEventListener('input', calculateTotals);
        }

        // Attach events to existing rows
        document.querySelectorAll('.item-row').forEach(row => attachItemEvents(row));
        calculateTotals();

        // Save new client
        document.getElementById('saveClientBtn').addEventListener('click', function() {
            const name = document.getElementById('clientName').value.trim();
            const email = document.getElementById('clientEmail').value.trim();
            const phone = document.getElementById('clientPhone').value.trim();
            const address = document.getElementById('clientAddress').value.trim();

            if (!name) {
                alert('Ju lutem shkruani emrin e klientit!');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add_client');
            formData.append('name', name);
            formData.append('email', email);
            formData.append('phone', phone);
            formData.append('address', address);

            fetch('index.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const select = document.getElementById('clientSelect');
                    const option = document.createElement('option');
                    option.value = data.id;
                    option.textContent = data.name;
                    select.appendChild(option);
                    select.value = data.id;
                    
                    document.getElementById('addClientModal').querySelector('.btn-close').click();
                    document.getElementById('addClientForm').reset();
                    alert('Klienti u shtua me sukses!');
                }
            })
            .catch(error => {
                alert('Gabim gjatë shtimit të klientit!');
                console.error(error);
            });
        });

        // Save new product
        document.getElementById('saveProductBtn').addEventListener('click', function() {
            const name = document.getElementById('productName').value.trim();
            const description = document.getElementById('productDescription').value.trim();
            const price = document.getElementById('productPrice').value;
            const vat_rate = document.getElementById('productVat').value || 20;

            if (!name || !price) {
                alert('Ju lutem shkruani emrin dhe çmimin e produktit!');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add_product');
            formData.append('name', name);
            formData.append('description', description);
            formData.append('price', price);
            formData.append('vat_rate', vat_rate);

            fetch('index.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Add to all product selects
                    document.querySelectorAll('.product-select').forEach(select => {
                        const option = document.createElement('option');
                        option.value = data.id;
                        option.dataset.price = data.price;
                        option.dataset.vat = data.vat_rate;
                        option.textContent = data.name + ' - ' + parseFloat(data.price).toFixed(2) + ' €';
                        select.appendChild(option);
                    });
                    
                    document.getElementById('addProductModal').querySelector('.btn-close').click();
                    document.getElementById('addProductForm').reset();
                    alert('Produkti u shtua me sukses!');
                }
            })
            .catch(error => {
                alert('Gabim gjatë shtimit të produktit!');
                console.error(error);
            });
        });

        // Reset modals when closed
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('hidden.bs.modal', function() {
                this.querySelector('form').reset();
            });
        });
    </script>
</body>
</html>