<?php
session_start();
require_once 'functions.php';
require_once 'document_template.php';

$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'proforma';
$message = '';
$preview_data = null;

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generate'])) {
    $type = $_POST['doc_type'];
    $doc_number = generateDocNumber($type);
    $doc_date = date('Y-m-d');
    $customer_name = $_POST['customer_name'];
    $customer_address = $_POST['customer_address'];
    $customer_phone = $_POST['customer_phone'];
    $customer_email = $_POST['customer_email'];

    // VAT toggle
    $vat_enabled = isset($_POST['vat_enabled']) ? true : false;

    $items = [];
    $subtotal = 0;

    // Process items (only description, quantity, unit_price)
    $descriptions = $_POST['description'];
    $quantities = $_POST['quantity'];
    $unit_prices = $_POST['unit_price'];

    for($i=0; $i<count($descriptions); $i++) {
        if(empty($descriptions[$i])) continue;
        $qty = floatval($quantities[$i]);
        $price = floatval($unit_prices[$i]);
        $amount = $qty * $price;
        $items[] = [
            'description' => $descriptions[$i],
            'quantity' => $qty,
            'unit_price' => $price,
            'discount' => 0,      // removed discount
            'vat' => 0            // per‑item VAT removed
        ];
        $subtotal += $amount;
    }

    // Compute global VAT
    $vat_rate = 0.16; // 16%
    $vat_amount = $vat_enabled ? ($subtotal * $vat_rate) : 0;
    $total = $subtotal + $vat_amount;

    $data = [
        'doc_type' => $type,
        'doc_number' => $doc_number,
        'doc_date' => $doc_date,
        'customer_name' => $customer_name,
        'customer_address' => $customer_address,
        'customer_phone' => $customer_phone,
        'customer_email' => $customer_email,
        'items' => $items,
        'subtotal' => $subtotal,
        'vat_amount' => $vat_amount,
        'total' => $total
    ];

    $id = saveDocument($data);
    $_SESSION['message'] = 'Document generated successfully!';
    header("Location: index.php?tab=$type&preview=$id");
    exit;
}

// Handle preview request
$preview_id = isset($_GET['preview']) ? intval($_GET['preview']) : null;
if($preview_id) {
    $preview_data = getDocument($preview_id);
}

// Handle search
$search = isset($_GET['search']) ? $_GET['search'] : '';
$documents = getDocuments($search);

// Get message from session
if(isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document System - PowerVentures</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-custom">
        <div class="container">
            <a class="navbar-brand" href="#">
                <img src="<?= COMPANY_LOGO ?>" alt="Logo" height="40"> <?= COMPANY_NAME ?>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <?php
                    $tabs = ['quotation' => 'Quotation', 'proforma' => 'Proforma Invoice', 'invoice' => 'Invoice', 'receipt' => 'Receipt'];
                    foreach($tabs as $key => $label) {
                        $active = ($active_tab == $key) ? 'active' : '';
                        echo "<li class='nav-item'><a class='nav-link $active' href='?tab=$key'>$label</a></li>";
                    }
                    ?>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <?php if($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?= $message ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Left: Form -->
            <div class="col-lg-6">
                <div class="card p-4 fade-in">
                    <h4 class="mb-3" style="color:#0d47a1;">
                        <i class="fas fa-file-alt"></i> New <?= ucfirst($active_tab) ?>
                    </h4>
                    <form method="POST" id="docForm">
                        <input type="hidden" name="doc_type" value="<?= $active_tab ?>">
                        <div class="row">
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Customer Name *</label>
                                <input type="text" name="customer_name" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label">Phone</label>
                                <input type="text" name="customer_phone" class="form-control">
                            </div>
                            <div class="col-md-12 mb-2">
                                <label class="form-label">Address</label>
                                <textarea name="customer_address" class="form-control" rows="2"></textarea>
                            </div>
                            <div class="col-md-12 mb-2">
                                <label class="form-label">Email</label>
                                <input type="email" name="customer_email" class="form-control">
                            </div>
                        </div>

                        <hr>
                        <h6>Items</h6>
                        <div id="itemsContainer">
                            <div class="item-row row g-2 mb-2">
                                <div class="col-6"><input type="text" name="description[]" class="form-control" placeholder="Description" required></div>
                                <div class="col-3"><input type="number" name="quantity[]" class="form-control qty" placeholder="Qty" value="1" step="any" required></div>
                                <div class="col-3"><input type="number" name="unit_price[]" class="form-control price" placeholder="Unit Price" step="any" required></div>
                                <div class="col-12 text-end mt-1">
                                    <button type="button" class="btn btn-danger btn-sm remove-item"><i class="fas fa-times"></i> Remove</button>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-secondary btn-sm mt-2" id="addItem"><i class="fas fa-plus"></i> Add Item</button>

                        <!-- VAT Toggle -->
                        <div class="form-check mt-3">
                            <input class="form-check-input" type="checkbox" name="vat_enabled" id="vatToggle" checked>
                            <label class="form-check-label" for="vatToggle">
                                Apply VAT (16%)
                            </label>
                        </div>

                        <div class="mt-3 d-flex justify-content-end">
                            <button type="submit" name="generate" class="btn btn-primary"><i class="fas fa-save"></i> Generate & Save</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Right: Preview / List -->
            <div class="col-lg-6">
                <?php if($preview_data): ?>
                    <div class="card p-3 fade-in">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="mb-0"><i class="fas fa-eye"></i> Preview</h5>
                            <div>
                                <a href="pdf.php?id=<?= $preview_data['id'] ?>" class="btn btn-success btn-sm" target="_blank"><i class="fas fa-download"></i> PDF</a>
                                <button class="btn btn-secondary btn-sm" onclick="window.location.href='?tab=<?= $active_tab ?>'"><i class="fas fa-times"></i> Close</button>
                            </div>
                        </div>
                        <div class="doc-preview">
                            <?= generateDocumentHTML($preview_data, $preview_data['doc_type']) ?>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="card p-3">
                        <h5><i class="fas fa-search"></i> Search Saved Documents</h5>
                        <form method="GET" class="d-flex">
                            <input type="hidden" name="tab" value="<?= $active_tab ?>">
                            <input type="text" name="search" class="form-control me-2" placeholder="Search by No., Customer..." value="<?= htmlspecialchars($search) ?>">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i></button>
                        </form>
                        <hr>
                        <div style="max-height:400px; overflow-y:auto;">
                            <table class="table table-sm table-hover">
                                <thead>
                                    <tr><th>#</th><th>Doc No.</th><th>Customer</th><th>Date</th><th>Total</th><th>Action</th></tr>
                                </thead>
                                <tbody>
                                    <?php if(count($documents) == 0): ?>
                                        <tr><td colspan="6" class="text-center">No documents found</td></tr>
                                    <?php else: ?>
                                        <?php foreach($documents as $doc): ?>
                                            <tr>
                                                <td><?= $doc['id'] ?></td>
                                                <td><?= $doc['doc_number'] ?></td>
                                                <td><?= $doc['customer_name'] ?></td>
                                                <td><?= date('d-m-Y', strtotime($doc['doc_date'])) ?></td>
                                                <td><?= number_format($doc['total'], 2) ?></td>
                                                <td>
                                                    <a href="?tab=<?= $active_tab ?>&preview=<?= $doc['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="fas fa-eye"></i></a>
                                                    <a href="pdf.php?id=<?= $doc['id'] ?>" class="btn btn-sm btn-outline-success" target="_blank"><i class="fas fa-download"></i></a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add item row
            document.getElementById('addItem').addEventListener('click', function() {
                let container = document.getElementById('itemsContainer');
                let row = container.querySelector('.item-row').cloneNode(true);
                row.querySelectorAll('input').forEach(input => input.value = '');
                row.querySelector('.qty').value = 1;
                container.appendChild(row);
            });

            // Remove item row
            document.getElementById('itemsContainer').addEventListener('click', function(e) {
                if(e.target.closest('.remove-item')) {
                    let rows = this.querySelectorAll('.item-row');
                    if(rows.length > 1) {
                        e.target.closest('.item-row').remove();
                    } else {
                        alert('At least one item required.');
                    }
                }
            });
        });
    </script>
</body>
</html>