<?php
declare(strict_types=1);

session_start();

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

// Get workspace from session or use default
$workspace = $_SESSION['workspace'] ?? $_GET['workspace'] ?? 'pixelvise';

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

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

// Get the most recent invoice for this company with client information
$stmt = $pdo->prepare("SELECT i.*, c.name as client_name FROM invoices i LEFT JOIN clients c ON i.client_id = c.id WHERE i.company_id = ? ORDER BY i.id DESC LIMIT 1");
$stmt->execute([$company['id']]);
$latestInvoice = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Get invoice settings
$settings = InvoiceSettings::get() ?? [];

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

$workspaceQuery = $workspace ? '?workspace=' . urlencode((string) $workspace) : '';
$currencyCode = $settings['currency'] ?? 'USD';
$statusLabel = ucfirst($latestInvoice['status'] ?? 'draft');
$viewInvoiceUrl = "/pdf.php?workspace=" . urlencode($workspace) . "&action=view&invoice_id=" . (int) $latestInvoice['id'];
$downloadInvoiceUrl = "/pdf.php?workspace=" . urlencode($workspace) . "&action=download&invoice_id=" . (int) $latestInvoice['id'];
$newInvoiceUrl = "/invoice_create.php" . $workspaceQuery;
$allInvoicesUrl = "/invoices.php" . $workspaceQuery;
$clientName = $latestInvoice['client_name'] ?? 'Client';
?>
<!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 Generated · Keelance</title>
    <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,
        ],
        [
            'label' => 'Create another',
            'url' => '/invoice_create.php',
            'type' => 'primary',
            'icon' => 'M12 4v16m8-8H4',
            '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 generated',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card success-hero">
                <div class="success-hero__body">
                    <p class="section-title">Invoice generated</p>
                    <h2 class="success-hero__headline">
                        <span class="success-hero__inline-icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path d="M20 6L9 17l-5-5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                            </svg>
                        </span>
                        Your invoice is ready to send
                    </h2>
                    <p class="success-hero__description">We’ve saved the invoice and it’s now available to share with your client.</p>

                    <div class="success-hero__meta">
                        <div class="success-hero__stat">
                            <span class="summary-label">Invoice number</span>
                            <span class="summary-value"><?= h($latestInvoice['invoice_number']) ?></span>
                        </div>
                        <div class="success-hero__stat">
                            <span class="summary-label">Client</span>
                            <span class="summary-value"><?= h($clientName) ?></span>
                        </div>
                        <div class="success-hero__stat">
                            <span class="summary-label">Amount</span>
                            <span class="summary-value"><?= h($currencyCode) ?> <?= number_format((float) ($latestInvoice['total'] ?? 0), 2) ?></span>
                        </div>
                        <div class="success-hero__stat">
                            <span class="summary-label">Status</span>
                            <span class="summary-chip"><?= h($statusLabel) ?></span>
                        </div>
                    </div>

                    <div class="success-actions">
                        <a href="<?= h($viewInvoiceUrl) ?>" class="btn-primary">View invoice</a>
                        <a href="<?= h($downloadInvoiceUrl) ?>" class="btn-secondary">Download PDF</a>
                        <a href="<?= h($newInvoiceUrl) ?>" class="btn-secondary">New invoice</a>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div style="padding-bottom: 16px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 16px;">
                    <p class="section-title">Invoice summary</p>
                </div>
                <div class="invoice-summary-grid">
                    <div class="summary-field">
                        <span class="summary-label">Issued on</span>
                        <span class="summary-value"><?= date('M j, Y', strtotime($latestInvoice['created_at'])) ?></span>
                    </div>
                    <div class="summary-field">
                        <span class="summary-label">Due date</span>
                        <span class="summary-value"><?= date('M j, Y', strtotime($latestInvoice['due_date'])) ?></span>
                    </div>
                    <div class="summary-field">
                        <span class="summary-label">Line items</span>
                        <span class="summary-value"><?= count(json_decode($latestInvoice['items_json'] ?? '[]', true) ?: []) ?></span>
                    </div>
                    <div class="summary-field">
                        <span class="summary-label">Workspace</span>
                        <span class="summary-value"><?= h($workspace) ?></span>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div style="padding-bottom: 16px; border-bottom: 1px solid var(--border-subtle); margin-bottom: 16px;">
                    <p class="section-title">Next steps</p>
                </div>
                <div class="next-steps">
                    <div class="next-step">
                        <div class="next-step__icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path d="M4 4h16v16H4z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                                <path d="M4 9h16" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                            </svg>
                        </div>
                        <div>
                            <p class="next-step__title">Share with client</p>
                            <p class="next-step__description">Send the secure invoice link or export a PDF copy for records.</p>
                        </div>
                        <a class="btn-secondary" href="<?= h($viewInvoiceUrl) ?>" style="margin-left: auto;">Open copy</a>
                    </div>
                    <div class="next-step">
                        <div class="next-step__icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path d="M9 12l2 2 4-4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                                <path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                            </svg>
                        </div>
                        <div>
                            <p class="next-step__title">Track payment</p>
                            <p class="next-step__description">Monitor the invoice from the invoices dashboard and add payments when received.</p>
                        </div>
                        <a class="btn-secondary" href="<?= h($allInvoicesUrl) ?>" style="margin-left: auto;">Go to list</a>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>

</body>
</html>
