<?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
debug_log("Index.php: Checking authentication...");
if (!AuthManager::isAuthenticated()) {
    debug_log("Index.php: Not authenticated, redirecting to login");
    header('Location: /login.php');
    exit;
}
debug_log("Index.php: Authenticated successfully");

// Handle workspace switch parameter from URL
$switchId = (int) ($_GET['switch'] ?? 0);
if ($switchId) {
    // Switch to new workspace
    $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;
        
        // Redirect to clean URL (remove switch parameter)
        header('Location: /index.php');
        exit;
    }
}

// Get company from session first (most reliable), then URL parameter
$company = null;
$workspaceParam = $_GET['workspace'] ?? null;
$pdo = getPDO();

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

// Priority 2: Use URL parameter if session company not found
if (!$company && $workspaceParam) {
    if (is_string($workspaceParam) && !is_numeric($workspaceParam)) {
        // Search by username
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE username = ?");
        $stmt->execute([$workspaceParam]);
        $company = $stmt->fetch();
    } else {
        // Search by ID
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([(int)$workspaceParam]);
        $company = $stmt->fetch();
    }
}

// Priority 3: Fallback to user's first company
if (!$company) {
    $user = AuthManager::getCurrentUser();
    if ($user && !empty($user['company_id'])) {
        $stmt = $pdo->prepare("SELECT c.* FROM companies c 
                              WHERE c.id = ?");
        $stmt->execute([$user['company_id']]);
        $company = $stmt->fetch();
    }
}

// Update session if we found a different company
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;

// Build workspace query fragments for links
$workspaceQuery = isset($company['username']) && $company['username'] !== ''
    ? '?workspace=' . urlencode($company['username'])
    : '';
$workspaceQueryWithPrefix = isset($company['username']) && $company['username'] !== ''
    ? '&workspace=' . urlencode($company['username'])
    : '';

// Debug: Log what we're actually using
error_log("INDEX - Company: " . ($company['name'] ?? 'none') . " (ID: " . ($company['id'] ?? 'none') . ", Username: " . ($company['username'] ?? 'none') . ")");

// Handle case where company is not found
if (!$companyId) {
    // Try to get company directly from AuthManager
    $company = AuthManager::getCurrentCompany();
    
    if (!$company) {
        // Get default 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. Please run the MySQL setup script first.");
        }
    } else {
        $companyId = $company['id'];
    }
}

// Get real stats - COMPANY SPECIFIC (using DatabaseHelper for safety)
$clientCount = DatabaseHelper::safeCount('clients', 'company_id = ?', [$companyId]);
$templateCount = DatabaseHelper::safeCount('templates', 'company_id = ?', [$companyId]);
$moduleCount = DatabaseHelper::safeCount('modules', 'company_id = ?', [$companyId]);
$proposalCount = DatabaseHelper::safeCount('proposals', 'company_id = ?', [$companyId]);
$contractCount = DatabaseHelper::safeCount('contracts', 'company_id = ?', [$companyId]);

// Invoice Statistics - COMPANY SPECIFIC (status-based so it works even if paid_amount is not used)
$invoiceStats = DatabaseHelper::safeQuery("
    SELECT 
        COUNT(*) AS total_invoices,
        SUM(total) AS total_amount,
        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);
$totalAmountRaw = (float)($invoiceStats['total_amount'] ?? 0);
$paidInvoices   = (int)($invoiceStats['paid_invoices'] ?? 0);

// Use status-based totals for dashboard cards
$totalRevenue = (float)($invoiceStats['total_paid'] ?? 0);
$totalDue     = (float)($invoiceStats['total_unpaid'] ?? 0);

// Get recent invoices - COMPANY SPECIFIC (safe)
$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]);

// Get settings for currency (safe)
$settings = DatabaseHelper::tableExists('invoice_settings') ? InvoiceSettings::get() : DatabaseHelper::getDefaultInvoiceSettings();

// Get recent proposals - COMPANY SPECIFIC (safe)
$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]);

// Get recent contracts - COMPANY SPECIFIC (safe)
$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]);

// Get system stats
$storageUsedMB = 0; // Placeholder - no PDF storage yet
$lastBackup = date('M j, Y H:i', strtotime('-2 hours')); // Placeholder

// Determine if the authenticated user has any workspaces
$user = AuthManager::getCurrentUser();
$userHasWorkspace = false;
if ($user) {
    $workspaceCount = DatabaseHelper::safeCount('user_company_access', 'user_id = ?', [$user['id']]);
    $userHasWorkspace = $workspaceCount > 0;
}

// Check for permission error message
$permissionError = $_SESSION['permission_error'] ?? null;
unset($_SESSION['permission_error']);

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

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen">
<div class="min-h-screen flex flex-col">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew(); ?>

    <main class="flex-1">
        <div class="max-w-5xl mx-auto px-4 py-6 space-y-6">
        
        <?php if ($permissionError): ?>
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <div class="flex">
                    <svg class="w-5 h-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                    </svg>
                    <div class="ml-3">
                        <p class="text-sm text-red-700"><?= htmlspecialchars($permissionError) ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if (!$userHasWorkspace): ?>
            <div class="mt-8">
                <div class="bg-white border border-dashed border-slate-300 rounded-xl p-6 sm:p-8 text-center shadow-sm">
                    <div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-50">
                        <svg class="h-6 w-6 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                        </svg>
                    </div>
                    <h1 class="text-xl sm:text-2xl font-semibold text-slate-900">You do not have any workspaces yet</h1>
                    <p class="mt-2 text-sm sm:text-base text-slate-600 max-w-xl mx-auto">
                        Workspaces keep your clients, documents and billing organized. Create your first workspace to start sending proposals, contracts and invoices.
                    </p>
                    <div class="mt-4 flex flex-col sm:flex-row items-center justify-center gap-3">
                        <a href="/workspace-plans.php" class="inline-flex items-center px-4 py-2 rounded-lg bg-emerald-600 text-white text-sm font-medium hover:bg-emerald-700 transition-colors duration-200">
                            <svg class="w-4 h-4 mr-2" 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>
                            Create Workspace
                        </a>
                        <a href="/workspace-plans.php" class="inline-flex items-center px-3 py-2 rounded-lg border border-slate-200 text-xs sm:text-sm font-medium text-slate-700 hover:border-slate-300 hover:text-slate-900 transition-colors duration-200">
                            Learn about plans
                        </a>
                    </div>
                </div>
            </div>
        <?php elseif (!$hasDashboardAccess): ?>
            <!-- No Dashboard Access -->
            <div class="mt-8">
                <div class="bg-white border border-amber-200 rounded-xl p-6 sm:p-8 text-center shadow-sm">
                    <div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-amber-50">
                        <svg class="h-6 w-6 text-amber-600" 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>
                    <h1 class="text-xl sm:text-2xl font-semibold text-slate-900">Dashboard Access Restricted</h1>
                    <p class="mt-2 text-sm sm:text-base text-slate-600 max-w-xl mx-auto">
                        You don't have permission to view the dashboard for <strong><?= htmlspecialchars($company['name'] ?? 'this workspace') ?></strong>.
                    </p>
                    <p class="mt-4 text-xs text-slate-500">
                        Contact the workspace owner to request access.
                    </p>
                </div>
            </div>
        <?php else: ?>
        <!-- Welcome Header -->
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
            <div>
                <h1 class="text-2xl font-bold text-slate-900">Dashboard</h1>
                <p class="text-slate-600 mt-1">Welcome back! Here's your business overview for <strong><?= htmlspecialchars($company['name'] ?? 'your workspace') ?></strong>.</p>
            </div>
        </div>

        <!-- Stats Overview -->
        <section class="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
            <div class="bg-white border border-slate-200 rounded-lg p-3 hover:shadow-md transition-all duration-300 hover:border-slate-300 group">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-slate-500 uppercase tracking-wide font-medium">Clients</p>
                        <p class="text-xl font-bold text-slate-900 mt-1 group-hover:text-blue-600 transition-colors duration-200"><?= $clientCount ?></p>
                    </div>
                    <div class="p-1.5 bg-blue-50 rounded-lg group-hover:bg-blue-100 transition-colors duration-200">
                        <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>
            <div class="bg-white border border-slate-200 rounded-lg p-3 hover:shadow-md transition-all duration-300 hover:border-slate-300 group">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-slate-500 uppercase tracking-wide font-medium">Proposals</p>
                        <p class="text-xl font-bold text-slate-900 mt-1 group-hover:text-amber-600 transition-colors duration-200"><?= $proposalCount ?></p>
                    </div>
                    <div class="p-1.5 bg-amber-50 rounded-lg group-hover:bg-amber-100 transition-colors duration-200">
                        <svg class="w-4 h-4 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>
            <div class="bg-white border border-slate-200 rounded-lg p-3 hover:shadow-md transition-all duration-300 hover:border-slate-300 group">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-slate-500 uppercase tracking-wide font-medium">Contracts</p>
                        <p class="text-xl font-bold text-slate-900 mt-1 group-hover:text-indigo-600 transition-colors duration-200"><?= $contractCount ?></p>
                    </div>
                    <div class="p-1.5 bg-indigo-50 rounded-lg group-hover:bg-indigo-100 transition-colors duration-200">
                        <svg class="w-4 h-4 text-indigo-600" 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>
            </div>
            <div class="bg-white border border-slate-200 rounded-lg p-3 hover:shadow-md transition-all duration-300 hover:border-slate-300 group">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-xs text-slate-500 uppercase tracking-wide font-medium">Invoices</p>
                        <p class="text-xl font-bold text-slate-900 mt-1 group-hover:text-emerald-600 transition-colors duration-200"><?= $invoiceCount ?></p>
                    </div>
                    <div class="p-1.5 bg-emerald-50 rounded-lg group-hover:bg-emerald-100 transition-colors duration-200">
                        <svg class="w-4 h-4 text-emerald-600" 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>
            </div>
        </section>

        <!-- Invoice Summary -->
        <section class="bg-gradient-to-br from-white to-slate-50 border border-slate-200 rounded-lg p-4 shadow-md">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-base font-semibold text-slate-900 flex items-center gap-2">
                    <div class="p-1.5 bg-emerald-100 rounded-lg">
                        <svg class="w-4 h-4 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    Invoice Overview
                </h2>
                <a href="/invoices.php" class="text-sm text-emerald-600 hover:text-emerald-700 font-medium flex items-center gap-1">
                    View Details
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </a>
            </div>
            <div class="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
                <div class="text-center p-3 bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-lg border border-emerald-200 hover:shadow-sm transition-all duration-300">
                    <div class="p-1.5 bg-emerald-500 rounded inline-block mb-2">
                        <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <p class="text-xl font-bold text-emerald-700"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalRevenue, 2) ?></p>
                    <p class="text-xs text-emerald-600 mt-1 font-medium">Total Paid</p>
                </div>
                <div class="text-center p-3 bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg border border-blue-200 hover:shadow-sm transition-all duration-300">
                    <div class="p-1.5 bg-blue-500 rounded inline-block mb-2">
                        <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <p class="text-xl font-bold text-blue-700"><?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $totalDue, 2) ?></p>
                    <p class="text-xs text-blue-600 mt-1 font-medium">Total Due</p>
                </div>
                <div class="text-center p-3 bg-gradient-to-br from-amber-50 to-amber-100 rounded-lg border border-amber-200 hover:shadow-sm transition-all duration-300">
                    <div class="p-1.5 bg-amber-500 rounded inline-block mb-2">
                        <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <p class="text-xl font-bold text-amber-700"><?= $paidInvoices ?></p>
                    <p class="text-xs text-amber-600 mt-1 font-medium">Paid Invoices</p>
                </div>
                <div class="text-center p-3 bg-gradient-to-br from-slate-50 to-slate-100 rounded-lg border border-slate-200 hover:shadow-sm transition-all duration-300">
                    <div class="p-1.5 bg-slate-600 rounded inline-block mb-2">
                        <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                        </svg>
                    </div>
                    <p class="text-xl font-bold text-slate-700"><?= $invoiceCount > 0 ? round(($paidInvoices / $invoiceCount) * 100, 0) : 0 ?>%</p>
                    <p class="text-xs text-slate-600 mt-1 font-medium">Payout Rate</p>
                </div>
            </div>
        </section>

        <!-- Quick Actions -->
        <section class="bg-white border border-slate-200 rounded-lg p-4 shadow-md">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-base font-semibold text-slate-900 flex items-center gap-2">
                    <div class="p-1.5 bg-blue-100 rounded-lg">
                        <svg class="w-4 h-4 text-blue-600" 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>
                    Quick Actions
                </h2>
            </div>
            <div class="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
                <a href="/clients.php?action=create<?= $workspaceQueryWithPrefix ?>" class="flex items-center gap-3 p-3 border border-slate-200 rounded-lg hover:bg-blue-50 hover:border-blue-300 transition-all duration-200 group">
                    <div class="p-2 bg-blue-100 rounded-lg group-hover:bg-blue-200 transition-colors duration-200">
                        <svg class="w-4 h-4 text-blue-600" 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="flex-1">
                        <p class="text-sm font-medium text-slate-900 group-hover:text-blue-700 transition-colors duration-200">Add Client</p>
                        <p class="text-xs text-slate-500">Create new client</p>
                    </div>
                </a>
                <a href="/invoice_create.php<?= $workspaceQuery ?>" class="flex items-center gap-3 p-3 border border-slate-200 rounded-lg hover:bg-emerald-50 hover:border-emerald-300 transition-all duration-200 group">
                    <div class="p-2 bg-emerald-100 rounded-lg group-hover:bg-emerald-200 transition-colors duration-200">
                        <svg class="w-4 h-4 text-emerald-600" 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="flex-1">
                        <p class="text-sm font-medium text-slate-900 group-hover:text-emerald-700 transition-colors duration-200">Invoice</p>
                        <p class="text-xs text-slate-500">Create invoice</p>
                    </div>
                </a>
                <a href="/contract_create.php<?= $workspaceQuery ?>" class="flex items-center gap-3 p-3 border border-slate-200 rounded-lg hover:bg-indigo-50 hover:border-indigo-300 transition-all duration-200 group">
                    <div class="p-2 bg-indigo-100 rounded-lg group-hover:bg-indigo-200 transition-colors duration-200">
                        <svg class="w-4 h-4 text-indigo-600" 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="flex-1">
                        <p class="text-sm font-medium text-slate-900 group-hover:text-indigo-700 transition-colors duration-200">Contract</p>
                        <p class="text-xs text-slate-500">Create contract</p>
                    </div>
                </a>
                <a href="/generate.php<?= isset($company['username']) ? '?workspace=' . urlencode($company['username']) : '' ?>" class="flex items-center gap-3 p-3 border border-slate-200 rounded-lg hover:bg-amber-50 hover:border-amber-300 transition-all duration-200 group">
                    <div class="p-2 bg-amber-100 rounded-lg group-hover:bg-amber-200 transition-colors duration-200">
                        <svg class="w-4 h-4 text-amber-600" 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="flex-1">
                        <p class="text-sm font-medium text-slate-900 group-hover:text-amber-700 transition-colors duration-200">Proposal</p>
                        <p class="text-xs text-slate-500">Generate proposal</p>
                    </div>
                </a>
            </div>
        </section>

        <!-- Recent Activity -->
        <section class="grid gap-4 lg:grid-cols-3">
            <div class="bg-white border border-slate-200 rounded-lg p-4 shadow-md hover:shadow-lg transition-all duration-300">
                <div class="flex items-center justify-between mb-3">
                    <a href="/invoices.php" class="text-sm font-semibold text-slate-900 hover:text-emerald-600 transition-colors duration-200 flex items-center gap-2">
                        <div class="p-1.5 bg-emerald-100 rounded-lg">
                            <svg class="w-4 h-4 text-emerald-600" 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>
                        Recent Invoices
                    </a>
                </div>
                <div class="space-y-3">
                    <?php foreach (array_slice($recentInvoices, 0, 3) as $invoice): ?>
                        <?php
                        $statusColors = [
                            'draft' => 'bg-gray-100 text-gray-700',
                            'created' => 'bg-blue-100 text-blue-700',
                            'sent' => 'bg-indigo-100 text-indigo-700',
                            'void' => 'bg-purple-100 text-purple-700',
                            'cancelled' => 'bg-red-100 text-red-700',
                            'unpaid' => 'bg-orange-100 text-orange-700',
                            'partially_paid' => 'bg-yellow-100 text-yellow-700',
                            'paid' => 'bg-green-100 text-green-700'
                        ];
                        $statusLabels = [
                            'draft' => 'Draft',
                            'created' => 'Created',
                            'sent' => 'Sent',
                            'void' => 'Void',
                            'cancelled' => 'Cancelled',
                            'unpaid' => 'Unpaid',
                            'partially_paid' => 'Partially Paid',
                            'paid' => 'Paid'
                        ];
                        ?>
                        <div class="flex items-center justify-between p-3 border border-slate-100 rounded-lg hover:bg-slate-50 transition-colors duration-200">
                            <div class="flex items-center gap-3 min-w-0 flex-1">
                                <div class="w-8 h-8 bg-slate-50 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <svg class="w-4 h-4 text-slate-600" 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="min-w-0 flex-1">
                                    <p class="text-sm font-medium text-slate-900 truncate"><?= h($invoice['invoice_number']) ?></p>
                                    <p class="text-xs text-slate-500 truncate"><?= h($invoice['client_name'] ?? 'Unknown') ?></p>
                                </div>
                            </div>
                            <div class="flex items-center gap-2 flex-shrink-0">
                                <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium <?= $statusColors[$invoice['status']] ?? 'bg-gray-100 text-gray-700' ?>">
                                    <?= h($statusLabels[$invoice['status']] ?? $invoice['status']) ?>
                                </span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php if (!$recentInvoices): ?>
                        <div class="text-center py-6">
                            <div class="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center mx-auto mb-2">
                                <svg class="w-5 h-5 text-slate-400" 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>
                            <p class="text-sm text-slate-500 mb-2">No invoices yet</p>
                            <a href="/invoice_create.php" class="inline-flex items-center px-3 py-1.5 bg-emerald-600 text-white text-sm rounded-lg hover:bg-emerald-700 transition-colors duration-200">
                                Create First Invoice
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="mt-3 pt-3 border-t border-slate-100">
                    <a href="/invoices.php" class="text-sm text-slate-600 hover:text-emerald-600 font-medium flex items-center gap-1">
                        View all invoices
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                    </a>
                </div>
            </div>

            <div class="bg-white border border-slate-200 rounded-lg p-4 shadow-md hover:shadow-lg transition-all duration-300">
                <div class="flex items-center justify-between mb-3">
                    <a href="/proposals.php" class="text-sm font-semibold text-slate-900 hover:text-amber-600 transition-colors duration-200 flex items-center gap-2">
                        <div class="p-1.5 bg-amber-100 rounded-lg">
                            <svg class="w-4 h-4 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        Recent Proposals
                    </a>
                </div>
                <div class="space-y-3">
                    <?php foreach (array_slice($recentProposals, 0, 3) as $proposal): ?>
                        <?php
                        $timeAgo = getTimeAgo($proposal['created_at']);
                        $clientInitials = getClientInitials($proposal['client_name'] ?? 'Unknown');
                        $proposalTitle = $proposal['title'] ?? 'Proposal #' . $proposal['id'];
                        $status = $proposal['status'] ?? 'draft';
                        $statusColor = $status === 'sent' ? 'green' : 'blue';
                        ?>
                        <div class="flex items-center justify-between p-3 border border-slate-100 rounded-lg hover:bg-slate-50 transition-colors duration-200">
                            <div class="flex items-center gap-3 min-w-0 flex-1">
                                <div class="w-8 h-8 bg-slate-50 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <span class="text-sm font-medium text-slate-600"><?= $clientInitials ?></span>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-medium text-slate-900 truncate"><?= h($proposalTitle) ?></p>
                                    <p class="text-xs text-slate-500 truncate"><?= h($proposal['client_name'] ?? 'Unknown') ?> • <?= h($proposal['proposal_number'] ?? 'PRO-' . $proposal['id']) ?></p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-<?= $statusColor ?>-100 text-<?= $statusColor ?>-700 flex-shrink-0">
                                <?= h(ucfirst($status)) ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                    <?php if (!$recentProposals): ?>
                        <div class="text-center py-6">
                            <div class="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center mx-auto mb-2">
                                <svg class="w-5 h-5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                            <p class="text-sm text-slate-500 mb-2">No proposals yet</p>
                            <a href="/generate.php<?= isset($company['username']) ? '?workspace=' . urlencode($company['username']) : '' ?>" class="inline-flex items-center px-3 py-1.5 bg-amber-600 text-white text-sm rounded-lg hover:bg-amber-700 transition-colors duration-200">
                                Create First Proposal
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="mt-3 pt-3 border-t border-slate-100">
                    <a href="/proposals.php" class="text-sm text-slate-600 hover:text-amber-600 font-medium flex items-center gap-1">
                        View all proposals
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                    </a>
                </div>
            </div>

            <div class="bg-white border border-slate-200 rounded-lg p-4 shadow-md hover:shadow-lg transition-all duration-300">
                <div class="flex items-center justify-between mb-3">
                    <a href="/contracts.php" class="text-sm font-semibold text-slate-900 hover:text-indigo-600 transition-colors duration-200 flex items-center gap-2">
                        <div class="p-1.5 bg-indigo-100 rounded-lg">
                            <svg class="w-4 h-4 text-indigo-600" 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>
                        Recent Contracts
                    </a>
                </div>
                <div class="space-y-3">
                    <?php foreach (array_slice($recentContracts, 0, 3) as $contract): ?>
                        <?php
                        $timeAgo = getTimeAgo($contract['created_at']);
                        $clientInitials = getClientInitials($contract['client_name'] ?? 'Unknown');
                        $contractTitle = $contract['title'] ?? 'Contract #' . $contract['id'];
                        $status = $contract['status'] ?? 'draft';
                        $statusColor = $status === 'signed' ? 'green' : ($status === 'pending' ? 'amber' : 'blue');
                        ?>
                        <div class="flex items-center justify-between p-3 border border-slate-100 rounded-lg hover:bg-slate-50 transition-colors duration-200">
                            <div class="flex items-center gap-3 min-w-0 flex-1">
                                <div class="w-8 h-8 bg-slate-50 rounded-lg flex items-center justify-center flex-shrink-0">
                                    <span class="text-sm font-medium text-slate-600"><?= $clientInitials ?></span>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-medium text-slate-900 truncate"><?= h($contractTitle) ?></p>
                                    <p class="text-xs text-slate-500 truncate"><?= h($contract['client_name'] ?? 'Unknown') ?></p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-<?= $statusColor ?>-100 text-<?= $statusColor ?>-700 flex-shrink-0">
                                <?= h(ucfirst($status)) ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                    <?php if (!$recentContracts): ?>
                        <div class="text-center py-6">
                            <div class="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center mx-auto mb-2">
                                <svg class="w-5 h-5 text-slate-400" 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>
                            <p class="text-sm text-slate-500 mb-2">No contracts yet</p>
                            <a href="/contract_create.php" class="inline-flex items-center px-3 py-1.5 bg-indigo-600 text-white text-sm rounded-lg hover:bg-indigo-700 transition-colors duration-200">
                                Create First Contract
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="mt-3 pt-3 border-t border-slate-100">
                    <a href="/contracts.php" class="text-sm text-slate-600 hover:text-indigo-600 font-medium flex items-center gap-1">
                        View all contracts
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                    </a>
                </div>
            </div>
        </section>
        <?php endif; ?>
        </div>
    </main>

    <?php include __DIR__ . '/footer.php'; ?>
</div>
</body>
</html>
