<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/TenantDB.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

// Check permission
requirePermission('invoices_edit');

$errors = [];
$successMessage = $_GET['success'] ?? null;
$editingItem = null;

// Get workspace from URL parameter or session
$workspace = $_GET['workspace'] ?? $_SESSION['workspace'] ?? null;

// Resolve company ID for logging based on workspace, with TenantDB fallback
$companyIdForLog = null;
if ($workspace && !is_array($workspace)) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT id FROM companies WHERE username = ?');
        $stmt->execute([$workspace]);
        $companyRow = $stmt->fetch();
        if ($companyRow && !empty($companyRow['id'])) {
            $companyIdForLog = (int) $companyRow['id'];
        }
    } catch (Throwable $e) {
        // ignore, will fall back to TenantDB
    }
}
if (!$companyIdForLog) {
    $tenantId = TenantDB::getTenant();
    if ($tenantId) {
        $companyIdForLog = (int) $tenantId;
    }
}

// Get all invoice items and tax brackets
$invoiceItems = ItemTemplate::all();
$taxBrackets = TaxBracket::getActive();
$settings = InvoiceSettings::get() ?? [];

// Handle item editing
if (isset($_GET['edit_item'])) {
    $editId = (int) $_GET['edit_item'];
    if ($editId > 0) {
        $editingItem = ItemTemplate::find($editId);
    }
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_item') {
        $data = [
            'description' => sanitizeText($_POST['name'] ?? ''),
            'sku' => sanitizeText($_POST['sku'] ?? ''),
            'unit_price' => (float) ($_POST['unit_price'] ?? 0),
            'tax_rate' => (float) ($_POST['default_tax_bracket_id'] ?? 0),
            'default_tax_bracket_id' => (int) ($_POST['default_tax_bracket_id'] ?? 0),
            'is_taxable' => isset($_POST['is_taxable']) ? 1 : 0,
        ];

        if (empty($data['description'])) {
            $errors[] = 'Item name is required.';
        } elseif ($data['unit_price'] < 0) {
            $errors[] = 'Unit price must be greater than or equal to 0.';
        } else {
            if (ItemTemplate::create($data)) {
                // Log invoice item creation (best-effort)
                try {
                    if ($companyIdForLog) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyIdForLog,
                            $userId ? (int) $userId : null,
                            'invoice_item_created',
                            'invoice_item',
                            null,
                            $data['description'] ?? null,
                            null,
                            $data
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }
                redirect('/invoice_items.php?workspace=' . urlencode($workspace), ['success' => 'Item added successfully!']);
            } else {
                $errors[] = 'Failed to add item.';
            }
        }
    }

    if ($action === 'update_item') {
        $itemId = (int) ($_POST['item_id'] ?? 0);
        if ($itemId > 0) {
            $oldItem = ItemTemplate::find($itemId);
            $data = [
                'description' => sanitizeText($_POST['name'] ?? ''),
                'sku' => sanitizeText($_POST['sku'] ?? ''),
                'unit_price' => (float) ($_POST['unit_price'] ?? 0),
                'tax_rate' => (float) ($_POST['default_tax_bracket_id'] ?? 0),
                'default_tax_bracket_id' => (int) ($_POST['default_tax_bracket_id'] ?? 0),
                'is_taxable' => isset($_POST['is_taxable']) ? 1 : 0,
            ];

            if (empty($data['description'])) {
                $errors[] = 'Item name is required.';
            } elseif ($data['unit_price'] < 0) {
                $errors[] = 'Unit price must be greater than or equal to 0.';
            } else {
                if (ItemTemplate::update($itemId, $data)) {
                    // Log invoice item update (best-effort)
                    try {
                        if ($companyIdForLog) {
                            $currentUser = AuthManager::getCurrentUser();
                            $userId = $currentUser['id'] ?? null;
                            ActivityLog::log(
                                (int) $companyIdForLog,
                                $userId ? (int) $userId : null,
                                'invoice_item_updated',
                                'invoice_item',
                                $itemId,
                                $data['description'] ?? null,
                                $oldItem,
                                $data
                            );
                        }
                    } catch (Throwable $e) {
                        // ignore logging failures
                    }
                    redirect('/invoice_items.php?workspace=' . urlencode($workspace), ['success' => 'Item updated successfully!']);
                } else {
                    $errors[] = 'Failed to update item.';
                }
            }
        }
    }

    if ($action === 'delete_item') {
        $itemId = (int) ($_POST['item_id'] ?? 0);
        if ($itemId > 0) {
            $oldItem = ItemTemplate::find($itemId);
            if (ItemTemplate::delete($itemId)) {
                // Log invoice item deletion (best-effort)
                try {
                    if ($companyIdForLog) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyIdForLog,
                            $userId ? (int) $userId : null,
                            'invoice_item_deleted',
                            'invoice_item',
                            $itemId,
                            $oldItem['description'] ?? null,
                            $oldItem,
                            null
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }
                redirect('/invoice_items.php?workspace=' . urlencode($workspace), ['success' => 'Item deleted successfully!']);
            } else {
                $errors[] = 'Failed to delete item.';
            }
        }
    }
}

// Refresh data after changes
$invoiceItems = ItemTemplate::all();
$taxBrackets = TaxBracket::getActive();

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$workspaceQuery = $workspace ? '?workspace=' . urlencode((string) $workspace) : '';
?>

<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Items · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Invoices', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'All invoices',
            'url' => '/invoices.php',
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
            'append_workspace' => true,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Invoices', 'url' => '/invoices.php', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ],
        currentPage: 'Invoice items',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <div style="display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-start; justify-content: space-between;">
                    <div>
                        <p class="section-title">Invoices</p>
                        <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Invoice items</h2>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Manage reusable items and default tax settings.</p>
                    </div>
                    <div style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                        <div class="input-with-icon" style="min-width: 220px;">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                            <input type="text" id="searchItems" class="input" placeholder="Search items...">
                        </div>
                        <span class="status-chip"><span id="itemCount"><?= count($invoiceItems) ?></span> items</span>
                    </div>
                </div>
            </section>
        </div>

        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <ul class="status-list">
                        <?php foreach ($errors as $error): ?>
                            <li><?= h($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        <?php endif; ?>

        <div class="dash-section">
            <section class="card">
                <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                    <div>
                        <p class="section-title"><?= $editingItem ? 'Edit item' : 'Add item' ?></p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin: 4px 0 0;">Create items you can reuse across invoices.</p>
                    </div>
                    <?php if ($editingItem): ?>
                        <a href="/invoice_items.php<?= $workspaceQuery ?>" class="btn-secondary btn-sm">Cancel edit</a>
                    <?php endif; ?>
                </div>

                <form method="POST">
                    <input type="hidden" name="action" value="<?= $editingItem ? 'update_item' : 'add_item' ?>">
                    <?php if ($editingItem): ?>
                        <input type="hidden" name="item_id" value="<?= (int) $editingItem['id'] ?>">
                    <?php endif; ?>

                    <div class="form-grid">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Item name</label>
                            <input type="text" name="name" value="<?= h($editingItem['description'] ?? '') ?>" required class="input" placeholder="e.g. Web development">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">SKU</label>
                            <input type="text" name="sku" value="<?= h($editingItem['sku'] ?? '') ?>" class="input" placeholder="e.g. WEB-001">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Unit price (<?= h($settings['currency'] ?? 'USD') ?>)</label>
                            <input type="number" name="unit_price" value="<?= h((string) ($editingItem['unit_price'] ?? 0)) ?>" step="0.01" min="0" required class="input" placeholder="0.00">
                        </div>
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-bottom: 4px;">Default tax bracket</label>
                            <select name="default_tax_bracket_id" class="input">
                                <option value="">No tax</option>
                                <?php foreach ($taxBrackets as $tax): ?>
                                    <option value="<?= (int) $tax['id'] ?>" <?= (int) ($editingItem['default_tax_bracket_id'] ?? 0) === (int) $tax['id'] ? 'selected' : '' ?>>
                                        <?= h($tax['name']) ?> (<?= number_format($tax['rate'] * 100, 2) ?>%)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div style="display: flex; align-items: center; gap: 8px; margin-top: 12px;">
                        <input type="checkbox" name="is_taxable" id="is_taxable" <?= ($editingItem['is_taxable'] ?? 1) ? 'checked' : '' ?>>
                        <label for="is_taxable" style="font-size: 11px; color: var(--text-secondary);">Taxable</label>
                    </div>

                    <div style="display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px;">
                        <button type="submit" class="btn-primary">
                            <?= $editingItem ? 'Update item' : 'Add item' ?>
                        </button>
                        <?php if (!$editingItem): ?>
                            <a href="/invoice_create.php<?= $workspaceQuery ?>" class="btn-secondary">Create invoice</a>
                        <?php endif; ?>
                    </div>
                </form>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div style="padding-bottom: 12px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 12px; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                    <div>
                        <p class="section-title">Items</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin: 4px 0 0;">Edit or delete items used in your invoices.</p>
                    </div>
                </div>

                <div class="table-shell">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>SKU</th>
                                <th>Price</th>
                                <th>Tax</th>
                                <th style="text-align: right;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody">
                            <?php if ($invoiceItems): ?>
                                <?php foreach ($invoiceItems as $item): ?>
                                    <?php
                                    $editUrl = '/invoice_items.php?edit_item=' . (int) $item['id'] . ($workspace ? '&workspace=' . urlencode((string) $workspace) : '');
                                    ?>
                                    <tr data-item-id="<?= (int) $item['id'] ?>">
                                        <td>
                                            <div style="display: flex; flex-direction: column; gap: 2px;">
                                                <div style="font-size: 13px; font-weight: 500; color: var(--text-primary);">
                                                    <?= h($item['description'] ?? '') ?>
                                                </div>
                                                <?php if ($item['is_taxable'] ?? false): ?>
                                                    <div><span class="status-chip">Taxable</span></div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td style="color: var(--text-secondary); font-size: 12px;">
                                            <?= h($item['sku'] ?? '—') ?>
                                        </td>
                                        <td style="font-weight: 500; color: var(--text-primary);">
                                            <?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) ($item['unit_price'] ?? 0), 2) ?>
                                        </td>
                                        <td style="color: var(--text-secondary); font-size: 12px;">
                                            <?php
                                            $taxLabel = 'No tax';
                                            if (!empty($item['default_tax_bracket_id'])) {
                                                foreach ($taxBrackets as $tax) {
                                                    if ((int) $tax['id'] === (int) $item['default_tax_bracket_id']) {
                                                        $taxLabel = ($tax['name'] ?? 'Tax') . ' (' . number_format(((float) $tax['rate']) * 100, 2) . '%)';
                                                        break;
                                                    }
                                                }
                                            }
                                            ?>
                                            <?= h($taxLabel) ?>
                                        </td>
                                        <td style="text-align: right;">
                                            <div style="display: flex; justify-content: flex-end; gap: 6px; flex-wrap: wrap;">
                                                <a href="<?= h($editUrl) ?>" class="btn-secondary btn-sm">Edit</a>
                                                <form method="POST" onsubmit="return confirm('Are you sure you want to delete this item?')" style="display: inline;">
                                                    <input type="hidden" name="action" value="delete_item">
                                                    <input type="hidden" name="item_id" value="<?= (int) $item['id'] ?>">
                                                    <button type="submit" class="btn-icon btn-icon--danger" aria-label="Delete item">
                                                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                        </svg>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" style="padding: 24px; text-align: center; color: var(--text-tertiary);">
                                        No invoice items found.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        </div>
    </div>
</div>

<script>
// Store items data for search
const items = <?= json_encode($invoiceItems) ?>;

// Search functionality
document.getElementById('searchItems').addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('#itemsTableBody tr');
    let visibleCount = 0;

    rows.forEach(row => {
        const itemId = row.getAttribute('data-item-id');
        if (itemId) {
            const item = items.find(i => i.id == itemId);
            if (item) {
                const searchableText = `${item.description ?? ''} ${item.sku ?? ''} ${item.unit_price ?? ''}`.toLowerCase();
                if (searchableText.includes(searchTerm)) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            }
        }
    });

    document.getElementById('itemCount').textContent = visibleCount;
});
</script>
</body>
</html>
