<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/../src/Invoice.php';
require_once __DIR__ . '/../src/Client.php';
require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/navigation.php';

$invoiceId = (int) ($_GET['id'] ?? 0);
$errors = [];
$successMessage = $_GET['success'] ?? null;

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

$workspaceParam = $_GET['workspace'] ?? null;
$companyDisplayName = 'Workspace';
$workspaceSlug = $workspaceParam;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

if ($invoiceId === 0) {
    redirect('/invoices.php' . ($workspace ? '?workspace=' . urlencode($workspace) : ''));
}

// Get workspace company for validation
$pdo = getPDO();
$stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
$stmt->execute([$workspace]);
$company = $stmt->fetch();

$companyDisplayName = $company['name'] ?? 'Workspace';
$workspaceSlug = $workspaceParam ?? ($company['username'] ?? null);
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

if (!$company) {
    redirect('/invoices.php' . ($workspace ? '?workspace=' . urlencode($workspace) : ''));
}

$invoice = Invoice::find($invoiceId);
$invoiceItems = Invoice::getInvoiceItems($invoiceId);
$settings = InvoiceSettings::get() ?? [];
$taxBrackets = TaxBracket::getActive();


if (!$invoice || $invoice['company_id'] != $company['id']) {
    $errors[] = 'Invoice not found or access denied.';
    redirect('/invoices.php' . ($workspace ? '?workspace=' . urlencode($workspace) : ''));
}

// Get payments for this invoice
$pdo = getPDO();
$stmt = $pdo->prepare('SELECT * FROM invoice_payments WHERE invoice_id = ? ORDER BY payment_date DESC');
$stmt->execute([$invoiceId]);
$payments = $stmt->fetchAll();

// Calculate total paid
$totalPaid = array_sum(array_column($payments, 'amount'));
$amountDue = $invoice['total'] - $totalPaid;

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

    if ($action === 'add_payment') {
        $amount = (float) ($_POST['amount'] ?? 0);
        $paymentDate = $_POST['payment_date'] ?? date('Y-m-d');
        $paymentMethod = $_POST['payment_method'] ?? '';
        $notes = $_POST['payment_notes'] ?? '';

        if ($amount > 0) {
            // Add payment record
            $stmt = $pdo->prepare('INSERT INTO invoice_payments (invoice_id, amount, payment_date, payment_method, notes, created_at) VALUES (?, ?, ?, ?, ?, NOW())');
            if ($stmt->execute([$invoiceId, $amount, $paymentDate, $paymentMethod, $notes])) {
                // Update invoice paid amount
                $stmt = $pdo->prepare('UPDATE invoices SET paid_amount = paid_amount + ?, status = ? WHERE id = ?');
                $newPaidAmount = $invoice['paid_amount'] + $amount;
                $newStatus = $newPaidAmount >= $invoice['total'] ? 'paid' : 'sent';
                $stmt->execute([$amount, $newStatus, $invoiceId]);
                
                // Log payment received in workspace activity (best-effort)
                workspace_log(
                    'payment_received',
                    'invoice',
                    (int) $invoiceId,
                    $invoice['invoice_number'] ?? null,
                    null,
                    [
                        'amount' => $amount,
                        'payment_date' => $paymentDate,
                        'payment_method' => $paymentMethod,
                        'new_status' => $newStatus,
                    ]
                );
                
                redirect('/invoice_view.php?id=' . $invoiceId . ($workspace ? '&workspace=' . urlencode($workspace) : ''), ['success' => 'Payment recorded successfully!']);
            } else {
                $errors[] = 'Failed to record payment.';
            }
        } else {
            $errors[] = 'Invalid payment amount.';
        }
    } elseif ($action === 'update_status') {
        $status = $_POST['status'] ?? '';
        $allowedStatuses = ['draft', 'sent', 'paid', 'overdue', 'void'];
        if (in_array($status, $allowedStatuses, true)) {
            if (Invoice::updateStatus($invoiceId, $status)) {
                redirect('/invoice_view.php?id=' . $invoiceId . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : ''), ['success' => 'Invoice status updated successfully!']);
            }
            $errors[] = 'Failed to update invoice status.';
        } else {
            $errors[] = 'Invalid status.';
        }
    } elseif ($action === 'delete_payment') {
        $paymentId = (int) ($_POST['payment_id'] ?? 0);
        if ($paymentId > 0) {
            $stmt = $pdo->prepare('SELECT id FROM invoice_payments WHERE id = ? AND invoice_id = ?');
            $stmt->execute([$paymentId, $invoiceId]);
            $existingPayment = $stmt->fetch();

            if ($existingPayment) {
                $deleteStmt = $pdo->prepare('DELETE FROM invoice_payments WHERE id = ? AND invoice_id = ?');
                if ($deleteStmt->execute([$paymentId, $invoiceId])) {
                    $sumStmt = $pdo->prepare('SELECT COALESCE(SUM(amount), 0) as total_paid FROM invoice_payments WHERE invoice_id = ?');
                    $sumStmt->execute([$invoiceId]);
                    $sumRow = $sumStmt->fetch();
                    $paidAmount = (float) ($sumRow['total_paid'] ?? 0);
                    $newStatus = $paidAmount >= (float) $invoice['total'] ? 'paid' : ($paidAmount > 0 ? 'sent' : 'draft');
                    $updateStmt = $pdo->prepare('UPDATE invoices SET paid_amount = ?, status = ? WHERE id = ?');
                    $updateStmt->execute([$paidAmount, $newStatus, $invoiceId]);

                    redirect('/invoice_view.php?id=' . $invoiceId . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : ''), ['success' => 'Payment deleted successfully!']);
                }
                $errors[] = 'Failed to delete payment.';
            } else {
                $errors[] = 'Payment not found.';
            }
        } else {
            $errors[] = 'Invalid payment.';
        }
    }
}

// Refresh data
$invoice = Invoice::find($invoiceId);
$invoiceItems = Invoice::getInvoiceItems($invoiceId);

// Payment method labels
$paymentMethods = [
    'cash' => 'Cash',
    'bank_transfer' => 'Bank Transfer',
    'check' => 'Check',
    'credit_card' => 'Credit Card',
    'paypal' => 'PayPal',
    'other' => 'Other'
];

// Status options
$statusOptions = [
    'draft' => 'Draft',
    'sent' => 'Sent',
    'paid' => 'Paid',
    'overdue' => 'Overdue',
    'void' => 'Void',
];

// Status badge colors (design system)
$statusColors = [
    'draft' => 'status-chip',
    'sent' => 'status-chip',
    'paid' => 'status-chip',
    'overdue' => 'status-chip',
    'void' => 'status-chip',
];

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

// Prepare data for invoice template
$invoiceData = [
    'id' => $invoice['id'],
    'invoice_number' => $invoice['invoice_number'],
    'issue_date' => $invoice['issue_date'],
    'due_date' => $invoice['due_date'],
    'invoice_subject' => $invoice['invoice_subject'] ?? '',
    'project_id' => $invoice['project_id'] ?? null,
    'proposal_id' => $invoice['proposal_id'] ?? null,
    'contract_id' => $invoice['contract_id'] ?? null,
    'notes' => $invoice['notes'] ?? '',
    'payment_terms' => $invoice['payment_terms'] ?? '',
    'tax_type' => $invoice['tax_method'] ?? 'per_item',
    'tax_exempt' => $invoice['tax_exempt'] ?? false,
    'tax_exemption_reason' => $invoice['tax_exemption_reason'] ?? '',
    'invoice_level_tax_bracket_id' => $invoice['invoice_level_tax_bracket_id'] ?? null,
    'subtotal' => $invoice['subtotal'],
    'tax_total' => $invoice['tax_amount'],
    'total' => $invoice['total'],
    'client_info' => [
        'name' => $invoice['client_name'] ?? 'Unknown Client',
        'email' => $invoice['client_email'] ?? '',
        'phone' => $invoice['client_phone'] ?? '',
        'address' => $invoice['client_address'] ?? '',
        'company_name' => $invoice['client_company'] ?? null,
    ],
    'display_name_option' => $invoice['display_name_option'] ?? $invoice['client_display_name_option'] ?? 'client_name',
    'custom_display_name' => $invoice['custom_display_name'] ?? $invoice['client_custom_display_name'] ?? null,
    'items' => array_map(function ($item) {
        return [
            'item_name' => $item['description'],
            'description' => $item['description'],
            'quantity' => $item['quantity'],
            'unit_price' => $item['unit_price'],
            'discount_percent' => 0,
            'tax_amount' => $item['total'] * ($item['tax_rate'] / 100),
            'tax_bracket_name' => $item['tax_bracket_name'] ?? null,
            'tax_bracket_rate' => $item['tax_rate'] ?? 0,
            'total' => $item['total'],
        ];
    }, $invoiceItems),
];

$displayName = '';
$displayOption = $invoiceData['display_name_option'];
if (empty($displayOption) || $displayOption === 'client_name') {
    if (!empty($invoiceData['client_info']['company_name'])) {
        $displayOption = 'company_name';
    }
}
switch ($displayOption) {
    case 'company_name':
        $displayName = $invoiceData['client_info']['company_name'] ?? $invoiceData['client_info']['name'];
        break;
    case 'custom':
        $displayName = $invoiceData['custom_display_name'] ?: $invoiceData['client_info']['name'];
        break;
    case 'client_name':
    default:
        $displayName = $invoiceData['client_info']['name'];
        break;
}
$invoiceData['display_name'] = $displayName;

if (!empty($invoiceData['invoice_level_tax_bracket_id'])) {
    $stmt = $pdo->prepare('SELECT * FROM tax_brackets WHERE id = ?');
    $stmt->execute([$invoiceData['invoice_level_tax_bracket_id']]);
    $taxBracket = $stmt->fetch();
    if ($taxBracket) {
        $invoiceData['invoice_level_tax_bracket'] = [
            'id' => $taxBracket['id'],
            'name' => $taxBracket['name'],
            'rate' => $taxBracket['rate'],
        ];
    }
}

$invoiceNumber = $invoice['invoice_number'] ?? 'DRAFT';
$settings = InvoiceSettings::get() ?? [];

// Render invoice template safely for embedding
ob_start();
include __DIR__ . '/../templates/invoice_template.php';
$invoiceTemplateHtml = (string) ob_get_clean();
$invoiceTemplateSrcdoc = htmlspecialchars($invoiceTemplateHtml, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
?>
<!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 <?= h($invoice['invoice_number'] ?? '') ?> · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <style>
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { background: white !important; }
        }
        .print-only { display: none; }
    </style>
</head>
<body>
<?php renderNavigationNew('Invoices', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [
        ['label' => 'Back to invoices', 'url' => '/invoices.php', 'type' => 'secondary', 'icon' => 'M10.5 19.5L3 12l7.5-7.5M3 12h18', 'append_workspace' => true],
        ['label' => 'Download PDF', 'url' => '/pdf.php?action=view&invoice_id=' . (int) $invoiceId, 'type' => 'secondary', 'icon' => 'M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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],
        ['label' => 'Print', 'url' => '#', 'type' => 'secondary', 'icon' => 'M6 9V2h12v7M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2M6 14h12v8H6v-8z'],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2z'],
        ],
        currentPage: 'Invoice ' . ($invoice['invoice_number'] ?? ''),
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

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

        <?php if ($errors): ?>
            <div class="dash-section no-print">
                <div class="status-banner error">
                    <div style="display: flex; flex-direction: column; gap: 4px;">
                        <strong style="font-size: 12px;">Error</strong>
                        <?php foreach ($errors as $error): ?>
                            <div><?= h($error) ?></div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($invoice): ?>
            <div class="dash-section">
                <section class="card template-hero">
                    <div>
                        <p class="section-title">Invoice</p>
                        <h1 class="template-hero__title"><?= h($invoice['invoice_number'] ?? ('INV-' . $invoiceId)) ?></h1>
                        <p class="template-hero__subtitle"><?= h($invoice['client_name'] ?? '') ?></p>
                    </div>
                    <div class="template-hero__meta">
                        <span class="status-chip"><?= h($statusOptions[$invoice['status']] ?? ($invoice['status'] ?? 'draft')) ?></span>
                        <span class="status-chip"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $invoice['total'], 2) ?> total</span>
                        <span class="status-chip"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $amountDue, 2) ?> due</span>
                    </div>
                </section>
            </div>

            <div class="dash-section no-print">
                <section class="card template-stats">
                    <div class="template-stats-grid">
                        <div class="template-stat">
                            <p class="template-stat__label">Invoice total</p>
                            <p class="template-stat__value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $invoice['total'], 2) ?></p>
                            <p class="template-stat__hint">Total billed</p>
                        </div>
                        <div class="template-stat">
                            <p class="template-stat__label">Total paid</p>
                            <p class="template-stat__value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalPaid, 2) ?></p>
                            <p class="template-stat__hint">Payments recorded</p>
                        </div>
                        <div class="template-stat">
                            <p class="template-stat__label">Amount due</p>
                            <p class="template-stat__value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $amountDue, 2) ?></p>
                            <p class="template-stat__hint">Outstanding balance</p>
                        </div>
                        <div class="template-stat">
                            <p class="template-stat__label">Status</p>
                            <form method="POST" style="margin: 0;">
                                <input type="hidden" name="action" value="update_status">
                                <select name="status" class="input" style="padding: 6px 10px; font-size: 12px;" onchange="this.form.submit()">
                                    <?php foreach ($statusOptions as $value => $label): ?>
                                        <option value="<?= $value ?>" <?= ($invoice['status'] ?? 'draft') === $value ? 'selected' : '' ?>><?= h($label) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </form>
                            <p class="template-stat__hint">Update invoice status</p>
                        </div>
                    </div>
                </section>
            </div>

            <div class="dash-section">
                <section class="card" style="padding: 0; overflow: hidden;">
                    <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                        <div>
                            <p class="section-title">Invoice document</p>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Print-ready layout</p>
                        </div>
                        <div class="no-print" style="display: flex; gap: 8px; flex-wrap: wrap;">
                            <a class="btn-secondary btn-sm" href="/download.php?action=view_invoice&invoice_id=<?= (int) $invoiceId ?><?= $workspaceQueryAmp ?>" target="_blank" style="white-space: nowrap;">Open</a>
                            <button type="button" class="btn-secondary btn-sm" onclick="window.print()" style="white-space: nowrap;">Print</button>
                        </div>
                    </div>
                    <div class="preview-surface" style="border-radius: 0; border: none;">
                        <div class="preview-paper" style="overflow: hidden;">
                            <iframe
                                title="Invoice preview"
                                srcdoc="<?= $invoiceTemplateSrcdoc ?>"
                                style="display: block; width: 100%; height: 1100px; border: 0; background: transparent;"
                            ></iframe>
                        </div>
                    </div>
                </section>
            </div>

            <div class="dash-section no-print">
                <section class="card" style="padding: 0; overflow: hidden;">
                    <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;">
                        <div>
                            <p class="section-title">Payment history</p>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">All recorded payments for this invoice</p>
                        </div>
                    </div>
                    <div style="overflow-x: auto;">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Amount</th>
                                    <th>Method</th>
                                    <th>Notes</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($payments): ?>
                                    <?php foreach ($payments as $payment): ?>
                                        <tr>
                                            <td><?= date('M j, Y', strtotime((string) $payment['payment_date'])) ?></td>
                                            <td><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $payment['amount'], 2) ?></td>
                                            <td><?= h($paymentMethods[$payment['payment_method']] ?? ucfirst(str_replace('_', ' ', (string) $payment['payment_method']))) ?></td>
                                            <td><?= h($payment['notes'] ?? '-') ?></td>
                                            <td style="text-align: right;">
                                                <div style="display: flex; justify-content: flex-end; gap: 8px; flex-wrap: wrap;">
                                                    <a href="/download.php?action=view_payment_receipt&payment_id=<?= (int) $payment['id'] ?>&invoice_id=<?= (int) $invoiceId ?><?= $workspaceQueryAmp ?>" class="btn-secondary btn-sm" target="_blank" style="white-space: nowrap;">Receipt</a>
                                                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete this payment?')" style="display: inline;">
                                                        <input type="hidden" name="action" value="delete_payment">
                                                        <input type="hidden" name="payment_id" value="<?= (int) $payment['id'] ?>">
                                                        <button type="submit" class="btn-danger btn-sm" style="white-space: nowrap;">Delete</button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5">
                                            <div class="empty-state">
                                                <h3>No payments recorded</h3>
                                                <p>Payments will appear here once recorded.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            </div>

            <?php if ($amountDue > 0): ?>
                <div class="dash-section no-print">
                    <section class="card">
                        <div style="margin-bottom: 16px;">
                            <p class="section-title">Record payment</p>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Amount due: <?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $amountDue, 2) ?></p>
                        </div>

                        <form method="POST" style="display: flex; flex-direction: column; gap: 12px;">
                            <input type="hidden" name="action" value="add_payment">

                            <div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px;">
                                <div style="grid-column: span 1;">
                                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Payment amount</label>
                                    <input type="number" name="amount" step="0.01" min="0" max="<?= (float) $amountDue ?>" required class="input">
                                </div>

                                <div style="grid-column: span 1;">
                                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Payment date</label>
                                    <input type="date" name="payment_date" required class="input">
                                </div>

                                <div style="grid-column: span 1;">
                                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Payment method</label>
                                    <select name="payment_method" required class="input">
                                        <option value="">Select method</option>
                                        <option value="cash">Cash</option>
                                        <option value="bank_transfer">Bank transfer</option>
                                        <option value="check">Check</option>
                                        <option value="credit_card">Credit card</option>
                                        <option value="paypal">PayPal</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>

                                <div style="grid-column: span 1;">
                                    <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Notes (optional)</label>
                                    <input type="text" name="payment_notes" class="input" placeholder="Payment notes">
                                </div>
                            </div>

                            <div style="display: flex; justify-content: flex-end;">
                                <button type="submit" class="btn-primary">Record payment</button>
                            </div>
                        </form>
                    </section>
                </div>
            <?php endif; ?>

        <?php endif; ?>
    </div>
</div>
<script>
document.addEventListener('click', function (event) {
    const el = event.target;
    if (!el) return;

    const anchor = el.closest('a[href="#"]');
    if (!anchor) return;

    event.preventDefault();
    const url = <?= json_encode('/download.php?action=view_invoice&invoice_id=' . (int) $invoiceId . $workspaceQueryAmp) ?>;
    const win = window.open(url, '_blank');
    if (!win) return;

    win.addEventListener('load', function () {
        try {
            win.focus();
            win.print();
        } catch (e) {
            // ignore
        }
    });
});
</script>

</body>
</html>
