<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/debug_logger.php';
require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/DatabaseHelper.php';
require_once __DIR__ . '/../src/InvoiceModels.php';

// Require authentication
if (!AuthManager::isAuthenticated()) {
    header('Location: /login.php');
    exit;
}

// Handle workspace switch
$switchId = (int) ($_GET['switch'] ?? 0);
if ($switchId) {
    $pdo = getPDO();
    $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
    $stmt->execute([$switchId]);
    $company = $stmt->fetch();
    if ($company) {
        $_SESSION['current_company_id'] = $company['id'];
        $_SESSION['current_company'] = $company;
        header('Location: /index.php');
        exit;
    }
}

// Get company
$company = null;
$workspaceParam = $_GET['workspace'] ?? null;
$pdo = getPDO();

if (isset($_SESSION['current_company_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
    $stmt->execute([$_SESSION['current_company_id']]);
    $company = $stmt->fetch();
}

if (!$company && $workspaceParam) {
    if (is_string($workspaceParam) && !is_numeric($workspaceParam)) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE username = ?");
        $stmt->execute([$workspaceParam]);
        $company = $stmt->fetch();
    } else {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([(int)$workspaceParam]);
        $company = $stmt->fetch();
    }
}

if (!$company) {
    $user = AuthManager::getCurrentUser();
    if ($user && !empty($user['company_id'])) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([$user['company_id']]);
        $company = $stmt->fetch();
    }
}

if ($company && (!isset($_SESSION['current_company_id']) || $_SESSION['current_company_id'] != $company['id'])) {
    $_SESSION['current_company_id'] = $company['id'];
    $_SESSION['current_company'] = $company;
}

$companyId = $company['id'] ?? null;
$workspaceQuery = isset($company['username']) && $company['username'] !== '' ? '?workspace=' . urlencode($company['username']) : '';
$workspaceQueryWithPrefix = isset($company['username']) && $company['username'] !== '' ? '&workspace=' . urlencode($company['username']) : '';

// Handle missing company
if (!$companyId) {
    $company = AuthManager::getCurrentCompany();
    if (!$company) {
        $stmt = $pdo->prepare("SELECT * FROM companies ORDER BY id LIMIT 1");
        $stmt->execute();
        $defaultCompany = $stmt->fetch();
        if ($defaultCompany) {
            TenantManager::setCurrentCompany($defaultCompany['id'], $defaultCompany);
            $companyId = $defaultCompany['id'];
        } else {
            die("No company found.");
        }
    } else {
        $companyId = $company['id'];
    }
}

// Get stats
$clientCount = DatabaseHelper::safeCount('clients', 'company_id = ?', [$companyId]);
$proposalCount = DatabaseHelper::safeCount('proposals', 'company_id = ?', [$companyId]);
$contractCount = DatabaseHelper::safeCount('contracts', 'company_id = ?', [$companyId]);

$invoiceStats = DatabaseHelper::safeQuery("
    SELECT 
        COUNT(*) AS total_invoices,
        COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid_invoices,
        SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS total_paid,
        SUM(CASE WHEN status <> 'paid' THEN total ELSE 0 END) AS total_unpaid
    FROM invoices WHERE company_id = ?
", [$companyId]);

$invoiceStats = $invoiceStats[0] ?? [];
$invoiceCount = (int)($invoiceStats['total_invoices'] ?? 0);
$paidInvoices = (int)($invoiceStats['paid_invoices'] ?? 0);
$totalRevenue = (float)($invoiceStats['total_paid'] ?? 0);
$totalDue = (float)($invoiceStats['total_unpaid'] ?? 0);

// Get recent items
$recentInvoices = DatabaseHelper::safeQuery("
    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.created_at DESC LIMIT 5
", [$companyId]);

$recentProposals = DatabaseHelper::safeQuery("
    SELECT p.*, c.name as client_name FROM proposals p
    LEFT JOIN clients c ON p.client_id = c.id
    WHERE p.company_id = ? ORDER BY p.created_at DESC LIMIT 5
", [$companyId]);

$recentContracts = DatabaseHelper::safeQuery("
    SELECT co.*, c.name as client_name FROM contracts co
    LEFT JOIN clients c ON co.client_id = c.id
    WHERE co.company_id = ? ORDER BY co.created_at DESC LIMIT 5
", [$companyId]);

$settings = DatabaseHelper::tableExists('invoice_settings') ? InvoiceSettings::get() : DatabaseHelper::getDefaultInvoiceSettings();

// User and permissions
$user = AuthManager::getCurrentUser();
$userHasWorkspace = false;
if ($user) {
    $workspaceCount = DatabaseHelper::safeCount('user_company_access', 'user_id = ?', [$user['id']]);
    $userHasWorkspace = $workspaceCount > 0;
}

require_once __DIR__ . '/../src/Permissions/PermissionManager.php';
$hasDashboardAccess = true;
if ($userHasWorkspace && $companyId) {
    $hasDashboardAccess = PermissionManager::hasPermission((int)$user['id'], (int)$companyId, 'dashboard_view');
}

$permissionError = $_SESSION['permission_error'] ?? null;
unset($_SESSION['permission_error']);

$currentTheme = $_GET['theme'] ?? 'dark';
?>
<!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>Dashboard - Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <style>
        /* Page base */
        body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
        body { background: #0f0f0f; color: rgba(255,255,255,0.9); }
        [data-theme='light'] body { background: #f5f5f4; color: #37352f; }
        
        /* Main layout */
        .main-container { margin-left: 224px; min-height: 100vh; }
        @media (max-width: 767px) { .main-container { margin-left: 0; } }
        
            </style>
</head>
<body>
    <?php require_once __DIR__ . '/components/navigation.php'; renderNavigationNew('Dashboard', $currentTheme); ?>

    <div class="main-container">
        <?php
        require_once __DIR__ . '/components/headers/page-header.php';
        
        $actions = [
            ['label' => 'Settings', 'url' => '/settings.php', 'type' => 'secondary', 'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z'],
            [
                'label' => 'New', 
                'type' => 'primary', 
                'icon' => 'M12 4v16m8-8H4',
                'dropdown' => [
                    ['label' => 'New Proposal', 'url' => '/generate.php', 'icon' => 'M13 10V3L4 14h7v7l9-11h-7z'],
                    ['label' => 'New Contract', 'url' => '/contract_create.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'],
                    ['label' => 'New Invoice', 'url' => '/invoice_create.php', 'icon' => 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z'],
                    ['label' => 'New Client', 'url' => '/clients.php?action=create', 'icon' => 'M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z', 'append_workspace' => true]
                ]
            ]
        ];
        
        renderPageHeader(
            breadcrumbs: [
                ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6']
            ],
            currentPage: $company['name'] ?? 'Dashboard',
            actions: $actions,
            workspaceQuery: $workspaceQuery
        );
        ?>

        <!-- Dashboard Styles -->
        <style>
            .dash-container { width: 100%; padding: 20px 16px; }
            @media (min-width: 768px) { .dash-container { padding: 24px 32px; } }
            
            .dash-section { margin-bottom: 20px; }
            .dash-section-title { font-size: 11px; font-weight: 500; text-transform: uppercase; letter-spacing: 0.03em; color: rgba(255,255,255,0.45); margin-bottom: 8px; }
            [data-theme='light'] .dash-section-title { color: rgba(55,53,47,0.45); }
            
            .dash-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
            @media (max-width: 767px) { .dash-stats { grid-template-columns: repeat(2, 1fr); } }
            
            .dash-stat { padding: 14px 16px; border-radius: 6px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.04); }
            .dash-stat:hover { background: rgba(255,255,255,0.05); }
            [data-theme='light'] .dash-stat { background: #fff; border: 1px solid rgba(0,0,0,0.08); }
            [data-theme='light'] .dash-stat:hover { background: #fafafa; }
            
            .dash-stat-label { font-size: 11px; color: rgba(255,255,255,0.5); margin-bottom: 4px; }
            [data-theme='light'] .dash-stat-label { color: rgba(55,53,47,0.5); }
            
            .dash-stat-value { font-size: 18px; font-weight: 600; color: rgba(255,255,255,0.9); }
            [data-theme='light'] .dash-stat-value { color: rgb(55,53,47); }
            
            .dash-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }
            @media (min-width: 1024px) { .dash-grid { grid-template-columns: repeat(4, 1fr); } }
            @media (max-width: 639px) { .dash-grid { grid-template-columns: 1fr; } }
            
            .dash-card { display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 6px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.04); transition: background 0.1s ease; cursor: pointer; text-decoration: none; }
            .dash-card:hover { background: rgba(255,255,255,0.06); }
            [data-theme='light'] .dash-card { background: #fff; border: 1px solid rgba(0,0,0,0.08); }
            [data-theme='light'] .dash-card:hover { background: #fafafa; }
            
            .dash-card-icon { width: 28px; height: 28px; border-radius: 4px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
            .dash-card-icon svg { width: 14px; height: 14px; }
            
            .dash-card-text { flex: 1; min-width: 0; }
            .dash-card-title { font-size: 12px; font-weight: 500; color: rgba(255,255,255,0.85); }
            [data-theme='light'] .dash-card-title { color: rgb(55,53,47); }
            
            .dash-list { border-radius: 6px; background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.04); }
            [data-theme='light'] .dash-list { background: #fff; border: 1px solid rgba(0,0,0,0.08); }
            
            .dash-list-header { display: flex; align-items: center; justify-content: space-between; padding: 10px 12px; border-bottom: 1px solid rgba(255,255,255,0.05); }
            [data-theme='light'] .dash-list-header { border-bottom-color: rgba(0,0,0,0.05); }
            
            .dash-list-title { font-size: 12px; font-weight: 500; color: rgba(255,255,255,0.85); }
            [data-theme='light'] .dash-list-title { color: rgb(55,53,47); }
            
            .dash-list-link { font-size: 11px; color: rgba(255,255,255,0.4); }
            .dash-list-link:hover { color: rgba(255,255,255,0.7); }
            [data-theme='light'] .dash-list-link { color: rgba(55,53,47,0.4); }
            [data-theme='light'] .dash-list-link:hover { color: rgb(55,53,47); }
            
            .dash-list-item { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; border-bottom: 1px solid rgba(255,255,255,0.03); }
            .dash-list-item:last-child { border-bottom: none; }
            [data-theme='light'] .dash-list-item { border-bottom-color: rgba(0,0,0,0.03); }
            
            .dash-list-item-title { font-size: 12px; color: rgba(255,255,255,0.8); }
            [data-theme='light'] .dash-list-item-title { color: rgb(55,53,47); }
            
            .dash-list-item-sub { font-size: 11px; color: rgba(255,255,255,0.4); }
            [data-theme='light'] .dash-list-item-sub { color: rgba(55,53,47,0.5); }
            
            .dash-badge { font-size: 10px; padding: 2px 6px; border-radius: 3px; font-weight: 500; }
            .dash-badge-success { background: rgba(16,185,129,0.15); color: #10b981; }
            .dash-badge-info { background: rgba(59,130,246,0.15); color: #3b82f6; }
            .dash-badge-default { background: rgba(255,255,255,0.08); color: rgba(255,255,255,0.5); }
            [data-theme='light'] .dash-badge-default { background: rgba(0,0,0,0.06); color: rgba(55,53,47,0.6); }
            
            .dash-empty { padding: 24px; text-align: center; font-size: 12px; color: rgba(255,255,255,0.4); }
            [data-theme='light'] .dash-empty { color: rgba(55,53,47,0.4); }
            
            .dash-cols-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
            @media (max-width: 1023px) { .dash-cols-3 { grid-template-columns: 1fr; } }
            
            .dash-empty-state { padding: 48px 24px; text-align: center; }
            .dash-empty-icon { width: 40px; height: 40px; margin: 0 auto 12px; border-radius: 50%; background: rgba(255,255,255,0.05); display: flex; align-items: center; justify-content: center; }
            .dash-empty-icon svg { width: 20px; height: 20px; opacity: 0.5; }
            [data-theme='light'] .dash-empty-icon { background: rgba(0,0,0,0.04); }
            .dash-empty-title { font-size: 13px; font-weight: 500; color: rgba(255,255,255,0.8); margin: 0 0 4px; }
            [data-theme='light'] .dash-empty-title { color: rgb(55,53,47); }
            .dash-empty-desc { font-size: 12px; color: rgba(255,255,255,0.45); margin: 0 0 16px; }
            [data-theme='light'] .dash-empty-desc { color: rgba(55,53,47,0.5); }
        </style>

        <div class="dash-container">
            <?php if ($permissionError): ?>
                <div style="padding: 12px; border-radius: 4px; background: rgba(239,68,68,0.1); color: #ef4444; font-size: 12px; margin-bottom: 16px;"><?= h($permissionError) ?></div>
            <?php endif; ?>

            <?php if (!$userHasWorkspace): ?>
                <div class="dash-empty-state">
                    <div class="dash-empty-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                    </div>
                    <p class="dash-empty-title">No workspaces yet</p>
                    <p class="dash-empty-desc">Create your first workspace to get started.</p>
                    <a href="/workspace-plans.php" class="header-btn header-btn-primary" style="display: inline-flex;">Create Workspace</a>
                </div>

            <?php elseif (!$hasDashboardAccess): ?>
                <div class="dash-empty-state">
                    <div class="dash-empty-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                    </div>
                    <p class="dash-empty-title">Access Restricted</p>
                    <p class="dash-empty-desc">Contact the workspace owner for access.</p>
                </div>

            <?php else: ?>
                <!-- Stats -->
                <div class="dash-section">
                    <div class="dash-stats">
                        <div class="dash-stat">
                            <div class="dash-stat-label">Clients</div>
                            <div class="dash-stat-value"><?= number_format($clientCount) ?></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Proposals</div>
                            <div class="dash-stat-value"><?= number_format($proposalCount) ?></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Contracts</div>
                            <div class="dash-stat-value"><?= number_format($contractCount) ?></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Invoices</div>
                            <div class="dash-stat-value"><?= number_format($invoiceCount) ?></div>
                        </div>
                    </div>
                </div>

                <!-- Revenue -->
                <div class="dash-section">
                    <div class="dash-section-title">Revenue</div>
                    <div class="dash-stats">
                        <div class="dash-stat">
                            <div class="dash-stat-label">Paid</div>
                            <div class="dash-stat-value" style="color: #10b981;"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($totalRevenue, 2) ?></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Outstanding</div>
                            <div class="dash-stat-value"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format($totalDue, 2) ?></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Paid Invoices</div>
                            <div class="dash-stat-value"><?= $paidInvoices ?><span style="font-size: 12px; font-weight: 400; opacity: 0.5;"> / <?= $invoiceCount ?></span></div>
                        </div>
                        <div class="dash-stat">
                            <div class="dash-stat-label">Collection Rate</div>
                            <div class="dash-stat-value"><?= $invoiceCount > 0 ? round(($paidInvoices / $invoiceCount) * 100, 0) : 0 ?>%</div>
                        </div>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="dash-section">
                    <div class="dash-section-title">Quick actions</div>
                    <div class="dash-grid">
                        <a href="/clients.php?action=create<?= $workspaceQueryWithPrefix ?>" class="dash-card">
                            <div class="dash-card-icon" style="background: rgba(59,130,246,0.15); color: #3b82f6;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path></svg>
                            </div>
                            <div class="dash-card-text">
                                <div class="dash-card-title">Add client</div>
                            </div>
                        </a>
                        <a href="/invoice_create.php<?= $workspaceQuery ?>" class="dash-card">
                            <div class="dash-card-icon" style="background: rgba(16,185,129,0.15); color: #10b981;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                            </div>
                            <div class="dash-card-text">
                                <div class="dash-card-title">Create invoice</div>
                            </div>
                        </a>
                        <a href="/contract_create.php<?= $workspaceQuery ?>" class="dash-card">
                            <div class="dash-card-icon" style="background: rgba(99,102,241,0.15); color: #6366f1;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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"></path></svg>
                            </div>
                            <div class="dash-card-text">
                                <div class="dash-card-title">Draft contract</div>
                            </div>
                        </a>
                        <a href="/generate.php<?= $workspaceQuery ?>" class="dash-card">
                            <div class="dash-card-icon" style="background: rgba(245,158,11,0.15); color: #f59e0b;">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
                            </div>
                            <div class="dash-card-text">
                                <div class="dash-card-title">New proposal</div>
                            </div>
                        </a>
                    </div>
                </div>

                <!-- Recent Activity -->
                <div class="dash-section">
                    <div class="dash-section-title">Recent activity</div>
                    <div class="dash-cols-3">
                        <!-- Invoices -->
                        <div class="dash-list">
                            <div class="dash-list-header">
                                <span class="dash-list-title">Invoices</span>
                                <a href="/invoices.php<?= $workspaceQuery ?>" class="dash-list-link">View all</a>
                            </div>
                            <?php if ($recentInvoices): foreach (array_slice($recentInvoices, 0, 4) as $inv): ?>
                                <div class="dash-list-item">
                                    <div style="min-width: 0; flex: 1;">
                                        <div class="dash-list-item-title"><?= h($inv['invoice_number']) ?></div>
                                        <div class="dash-list-item-sub"><?= h($inv['client_name'] ?? 'Unknown') ?></div>
                                    </div>
                                    <span class="dash-badge <?= $inv['status'] === 'paid' ? 'dash-badge-success' : ($inv['status'] === 'sent' ? 'dash-badge-info' : 'dash-badge-default') ?>"><?= ucfirst($inv['status']) ?></span>
                                </div>
                            <?php endforeach; else: ?>
                                <div class="dash-empty">No invoices yet</div>
                            <?php endif; ?>
                        </div>

                        <!-- Proposals -->
                        <div class="dash-list">
                            <div class="dash-list-header">
                                <span class="dash-list-title">Proposals</span>
                                <a href="/proposals.php<?= $workspaceQuery ?>" class="dash-list-link">View all</a>
                            </div>
                            <?php if ($recentProposals): foreach (array_slice($recentProposals, 0, 4) as $prop): ?>
                                <div class="dash-list-item">
                                    <div style="min-width: 0; flex: 1;">
                                        <div class="dash-list-item-title"><?= h($prop['title'] ?? 'Proposal #' . $prop['id']) ?></div>
                                        <div class="dash-list-item-sub"><?= h($prop['client_name'] ?? 'Unknown') ?></div>
                                    </div>
                                    <?php $status = $prop['status'] ?? 'draft'; ?>
                                    <span class="dash-badge <?= $status === 'sent' ? 'dash-badge-success' : 'dash-badge-default' ?>"><?= ucfirst($status) ?></span>
                                </div>
                            <?php endforeach; else: ?>
                                <div class="dash-empty">No proposals yet</div>
                            <?php endif; ?>
                        </div>

                        <!-- Contracts -->
                        <div class="dash-list">
                            <div class="dash-list-header">
                                <span class="dash-list-title">Contracts</span>
                                <a href="/contracts.php<?= $workspaceQuery ?>" class="dash-list-link">View all</a>
                            </div>
                            <?php if ($recentContracts): foreach (array_slice($recentContracts, 0, 4) as $con): ?>
                                <div class="dash-list-item">
                                    <div style="min-width: 0; flex: 1;">
                                        <div class="dash-list-item-title"><?= h($con['title'] ?? 'Contract #' . $con['id']) ?></div>
                                        <div class="dash-list-item-sub"><?= h($con['client_name'] ?? 'Unknown') ?></div>
                                    </div>
                                    <?php $status = $con['status'] ?? 'draft'; ?>
                                    <span class="dash-badge <?= $status === 'signed' ? 'dash-badge-success' : 'dash-badge-default' ?>"><?= ucfirst($status) ?></span>
                                </div>
                            <?php endforeach; else: ?>
                                <div class="dash-empty">No contracts yet</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    </body>
</html>
