<?php
session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];
$edit_id = $_GET['id'] ?? 0;
$document = null;
$items = [];

if ($edit_id) {
    $stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ? AND company_id = ?");
    $stmt->execute([$edit_id, $companyId]);
    $document = $stmt->fetch();
    if ($document) {
        $stmt = $pdo->prepare("SELECT * FROM document_items WHERE document_id = ?");
        $stmt->execute([$edit_id]);
        $items = $stmt->fetchAll();
    }
}

$stmt = $pdo->prepare("SELECT * FROM clients WHERE company_id = ? ORDER BY name");
$stmt->execute([$companyId]);
$clients = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT * FROM products WHERE company_id = ? ORDER BY name");
$stmt->execute([$companyId]);
$products = $stmt->fetchAll();

$type = $_GET['type'] ?? ($document['type'] ?? 'invoice');
include 'includes/header.php';
?>

<div class="max-w-5xl mx-auto">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white"><?php echo $edit_id ? 'Edit' : 'Create'; ?> <?php echo ucfirst($type); ?></h1>
        <a href="documents.php" class="text-gray-600 dark:text-gray-400 hover:text-gray-800"><i class="fas fa-arrow-left mr-2"></i>Back to Documents</a>
    </div>

    <form id="documentForm" method="POST" action="document-save.php">
        <input type="hidden" name="id" value="<?php echo $edit_id; ?>">
        <input type="hidden" name="type" value="<?php echo $type; ?>">

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Document Number</label><input type="text" name="document_number" value="<?php echo htmlspecialchars($document['document_number'] ?? generateDocumentNumber($pdo, $companyId, $type)); ?>" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Issue Date</label><input type="date" name="issue_date" value="<?php echo $document ? $document['issue_date'] : date('Y-m-d'); ?>" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Due Date</label><input type="date" name="due_date" value="<?php echo $document['due_date'] ?? ''; ?>" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
            </div>
            <div class="mt-4"><label class="block text-gray-700 dark:text-gray-300 mb-1">Select Client</label><select name="client_id" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"><option value="">-- Select Client --</option><?php foreach ($clients as $client): ?><option value="<?php echo $client['id']; ?>" <?php echo ($document && $document['client_id'] == $client['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($client['name']); ?></option><?php endforeach; ?></select></div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Items</h3>
            <div id="itemsContainer">
                <?php if (empty($items)): ?>
                    <div class="item-row grid grid-cols-12 gap-2 mb-3 items-end">
                        <div class="col-span-5"><label class="block text-xs text-gray-500 dark:text-gray-400">Description</label><input type="text" name="item_description[]" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white" placeholder="Item description"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Quantity</label><input type="number" step="0.01" name="item_qty[]" value="1" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Unit Price</label><input type="number" step="0.01" name="item_price[]" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Tax %</label><input type="number" step="0.01" name="item_tax[]" value="<?php echo $company['default_tax_rate']; ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-1"><button type="button" onclick="removeItem(this)" class="text-red-600"><i class="fas fa-trash"></i></button></div>
                    </div>
                <?php else: foreach ($items as $item): ?>
                    <div class="item-row grid grid-cols-12 gap-2 mb-3 items-end">
                        <div class="col-span-5"><label class="block text-xs text-gray-500 dark:text-gray-400">Description</label><input type="text" name="item_description[]" value="<?php echo htmlspecialchars($item['description']); ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Quantity</label><input type="number" step="0.01" name="item_qty[]" value="<?php echo $item['quantity']; ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Unit Price</label><input type="number" step="0.01" name="item_price[]" value="<?php echo $item['unit_price']; ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Tax %</label><input type="number" step="0.01" name="item_tax[]" value="<?php echo $item['tax_rate']; ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                        <div class="col-span-1"><button type="button" onclick="removeItem(this)" class="text-red-600"><i class="fas fa-trash"></i></button></div>
                    </div>
                <?php endforeach; endif; ?>
            </div>
            <button type="button" onclick="addItem()" class="mt-2 text-blue-600"><i class="fas fa-plus mr-1"></i>Add Item</button>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Discount Type</label><select name="discount_type" id="discountType" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"><option value="percentage">Percentage (%)</option><option value="fixed">Fixed Amount</option></select></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Discount Value</label><input type="number" step="0.01" name="discount_value" id="discountValue" value="0" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
            </div>
            <div class="mt-4"><label class="block text-gray-700 dark:text-gray-300 mb-1">Notes</label><textarea name="notes" rows="3" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"><?php echo htmlspecialchars($document['notes'] ?? ''); ?></textarea></div>
            <div class="mt-4"><label class="block text-gray-700 dark:text-gray-300 mb-1">Terms & Conditions</label><textarea name="terms" rows="3" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"><?php echo htmlspecialchars($document['terms'] ?? ''); ?></textarea></div>
        </div>

        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
            <div class="flex justify-end"><div class="w-64"><div class="flex justify-between py-2"><span class="text-gray-600 dark:text-gray-400">Subtotal:</span><span id="subtotalDisplay" class="dark:text-white">0.00</span></div><div class="flex justify-between py-2"><span class="text-gray-600 dark:text-gray-400">Discount:</span><span id="discountDisplay" class="dark:text-white">0.00</span></div><div class="flex justify-between py-2"><span class="text-gray-600 dark:text-gray-400">Tax:</span><span id="taxDisplay" class="dark:text-white">0.00</span></div><div class="flex justify-between py-2 font-bold"><span class="text-gray-800 dark:text-white">Total:</span><span id="totalDisplay" class="text-gray-800 dark:text-white">0.00</span></div></div></div>
            <input type="hidden" name="subtotal" id="subtotalInput"><input type="hidden" name="tax_amount" id="taxInput"><input type="hidden" name="discount_amount" id="discountInput"><input type="hidden" name="total" id="totalInput"><input type="hidden" name="status" value="draft">
        </div>

        <div class="flex justify-end space-x-3"><button type="submit" name="action" value="save_draft" class="px-6 py-2 border rounded-lg hover:bg-gray-100 dark:border-gray-600 dark:text-gray-300">Save as Draft</button><button type="submit" name="action" value="save_send" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save & Send</button></div>
    </form>
</div>

<script>
function addItem() { const container = document.getElementById('itemsContainer'); const div = document.createElement('div'); div.className = 'item-row grid grid-cols-12 gap-2 mb-3 items-end'; div.innerHTML = '<div class="col-span-5"><label class="block text-xs text-gray-500 dark:text-gray-400">Description</label><input type="text" name="item_description[]" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div><div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Quantity</label><input type="number" step="0.01" name="item_qty[]" value="1" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div><div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Unit Price</label><input type="number" step="0.01" name="item_price[]" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div><div class="col-span-2"><label class="block text-xs text-gray-500 dark:text-gray-400">Tax %</label><input type="number" step="0.01" name="item_tax[]" value="<?php echo $company['default_tax_rate']; ?>" class="w-full px-2 py-1 border rounded text-sm dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div><div class="col-span-1"><button type="button" onclick="removeItem(this)" class="text-red-600"><i class="fas fa-trash"></i></button></div>'; container.appendChild(div); attachItemEvents(div); }
function removeItem(btn) { btn.closest('.item-row').remove(); calculateTotals(); }
function attachItemEvents(container) { const inputs = container.querySelectorAll('input'); inputs.forEach(input => input.addEventListener('input', calculateTotals)); }
function calculateTotals() { let subtotal = 0; document.querySelectorAll('.item-row').forEach(row => { const qty = parseFloat(row.querySelector('input[name*="qty"]')?.value) || 0; const price = parseFloat(row.querySelector('input[name*="price"]')?.value) || 0; subtotal += qty * price; }); const discountType = document.getElementById('discountType').value; const discountValue = parseFloat(document.getElementById('discountValue').value) || 0; let discountAmount = 0; if (discountType === 'percentage') discountAmount = subtotal * (discountValue / 100); else discountAmount = discountValue; const afterDiscount = subtotal - discountAmount; let taxAmount = 0; document.querySelectorAll('.item-row').forEach(row => { const qty = parseFloat(row.querySelector('input[name*="qty"]')?.value) || 0; const price = parseFloat(row.querySelector('input[name*="price"]')?.value) || 0; const tax = parseFloat(row.querySelector('input[name*="tax"]')?.value) || 0; const itemSubtotal = qty * price; const itemDiscountShare = (itemSubtotal / subtotal) * discountAmount; const taxable = itemSubtotal - itemDiscountShare; taxAmount += taxable * (tax / 100); }); const total = afterDiscount + taxAmount; document.getElementById('subtotalDisplay').innerText = subtotal.toFixed(2); document.getElementById('discountDisplay').innerText = discountAmount.toFixed(2); document.getElementById('taxDisplay').innerText = taxAmount.toFixed(2); document.getElementById('totalDisplay').innerText = total.toFixed(2); document.getElementById('subtotalInput').value = subtotal.toFixed(2); document.getElementById('discountInput').value = discountAmount.toFixed(2); document.getElementById('taxInput').value = taxAmount.toFixed(2); document.getElementById('totalInput').value = total.toFixed(2); }
document.querySelectorAll('#discountType, #discountValue').forEach(el => el.addEventListener('input', calculateTotals)); document.querySelectorAll('.item-row').forEach(row => attachItemEvents(row)); calculateTotals();
</script>

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