<?php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';

// Require authentication
AuthManager::requireAuth();

// Initialize tenant context
TenantManager::initialize();

// Get current user and company
$user = AuthManager::getCurrentUser();
$company = TenantManager::getCurrentCompany();

// Handle case where company is not found
if (!$company) {
    // Try to get company directly from AuthManager
    $company = AuthManager::getCurrentCompany();
    
    if (!$company) {
        // Create a default company if none exists
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT * FROM companies ORDER BY id LIMIT 1");
        $stmt->execute();
        $defaultCompany = $stmt->fetch();
        
        if ($defaultCompany) {
            // Set this as the current company
            TenantManager::setCurrentCompany($defaultCompany['id'], $defaultCompany);
            $company = $defaultCompany;
        } else {
            // No company exists - this shouldn't happen with proper setup
            die("No company found. Please run the MySQL setup script first.");
        }
    }
}

// Get subscription info (now safe with company ID)
$subscription = SubscriptionManager::getCompanySubscription($company['id']);

// Get usage metrics
$usage = [
    'proposals_this_month' => TenantManager::getCurrentUsage('proposals_per_month'),
    'total_clients' => TenantManager::getCurrentUsage('clients'),
    'total_users' => TenantManager::getCurrentUsage('users')
];

// Get recent activity
$pdo = getPDO();
$recentActivity = [];

// Recent proposals
$stmt = $pdo->prepare("
    SELECT 'proposal' as type, title, created_at, id 
    FROM proposals 
    WHERE company_id = ? 
    ORDER BY created_at DESC 
    LIMIT 3
");
$stmt->execute([$company['id']]);
$recentActivity = array_merge($recentActivity, $stmt->fetchAll());

// Recent invoices
$stmt = $pdo->prepare("
    SELECT 'invoice' as type, invoice_number as title, created_at, id 
    FROM invoices 
    WHERE company_id = ? 
    ORDER BY created_at DESC 
    LIMIT 3
");
$stmt->execute([$company['id']]);
$recentActivity = array_merge($recentActivity, $stmt->fetchAll());

// Sort by date
usort($recentActivity, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

$recentActivity = array_slice($recentActivity, 0, 5);

// Get user's workspaces
$userWorkspaces = TenantManager::getUserCompanies($user['id']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?= htmlspecialchars($company['name']) ?> | Keelance</title>
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <!-- Top Navigation -->
    <nav class="bg-white shadow-sm border-b border-gray-200">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center">
                        <i class="fas fa-rocket text-blue-600 text-2xl mr-3"></i>
                        <span class="text-xl font-bold text-gray-900">Keelance</span>
                    </div>
                    
                    <!-- Workspace Selector -->
                    <?php if (count($userWorkspaces) > 1): ?>
                    <div class="ml-8">
                        <select id="workspaceSelector" onchange="switchWorkspace(this.value)" 
                                class="text-sm border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
                            <?php foreach ($userWorkspaces as $workspace): ?>
                                <option value="<?= $workspace['id'] ?>" <?= $workspace['id'] == $company['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($workspace['name']) ?>
                                    <?php if ($workspace['role'] !== 'member'): ?>
                                        <span class="text-xs text-gray-500">(<?= ucfirst($workspace['role']) ?>)</span>
                                    <?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="flex items-center space-x-4">
                    <!-- Subscription Status -->
                    <div class="flex items-center space-x-2">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
                            <?= $subscription['subscription_status'] === 'active' ? 'bg-green-100 text-green-800' : 
                               ($subscription['subscription_status'] === 'trial' ? 'bg-blue-100 text-blue-800' : 'bg-yellow-100 text-yellow-800') ?>">
                            <?= ucfirst($subscription['subscription_status']) ?>
                        </span>
                        <?php if ($subscription['subscription_status'] === 'trial'): ?>
                            <span class="text-xs text-gray-500">
                                <?= date('M j, Y', strtotime($subscription['subscription_expires_at'])) ?>
                            </span>
                        <?php endif; ?>
                    </div>

                    <!-- Notifications -->
                    <button class="text-gray-400 hover:text-gray-500">
                        <i class="fas fa-bell"></i>
                    </button>

                    <!-- User Menu -->
                    <div class="relative">
                        <button onclick="toggleUserMenu()" class="flex items-center text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            <div class="h-8 w-8 rounded-full bg-blue-500 flex items-center justify-center">
                                <span class="text-white font-medium"><?= strtoupper(substr($user['name'], 0, 1)) ?></span>
                            </div>
                        </button>
                        
                        <div id="userMenu" class="hidden origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5">
                            <div class="py-1">
                                <a href="/profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fas fa-user mr-2"></i> Profile
                                </a>
                                <a href="/settings.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fas fa-cog mr-2"></i> Settings
                                </a>
                                <a href="/billing.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fas fa-credit-card mr-2"></i> Billing
                                </a>
                                <hr class="my-1">
                                <a href="/logout.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">
                                    <i class="fas fa-sign-out-alt mr-2"></i> Sign out
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Welcome Header -->
        <div class="mb-8">
            <h1 class="text-2xl font-bold text-gray-900">
                Welcome back, <?= htmlspecialchars($user['name']) ?>!
            </h1>
            <p class="mt-1 text-sm text-gray-600">
                Here's what's happening at <?= htmlspecialchars($company['name']) ?> today.
            </p>
        </div>

        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- Proposals This Month -->
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                                <i class="fas fa-file-contract text-white text-sm"></i>
                            </div>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Proposals This Month</dt>
                                <dd class="text-lg font-medium text-gray-900"><?= $usage['proposals_this_month'] ?></dd>
                            </dl>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-5 py-3">
                    <div class="text-sm">
                        <?php
                        $limit = $subscription['limits']['proposals_per_month'];
                        if ($limit === -1) {
                            echo '<span class="text-green-600 font-medium">Unlimited</span>';
                        } else {
                            $percentage = ($usage['proposals_this_month'] / $limit) * 100;
                            $color = $percentage >= 90 ? 'text-red-600' : ($percentage >= 70 ? 'text-yellow-600' : 'text-green-600');
                            echo "<span class='{$color} font-medium'>{$usage['proposals_this_month']} / {$limit}</span>";
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- Total Clients -->
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                                <i class="fas fa-users text-white text-sm"></i>
                            </div>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Total Clients</dt>
                                <dd class="text-lg font-medium text-gray-900"><?= $usage['total_clients'] ?></dd>
                            </dl>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-5 py-3">
                    <div class="text-sm">
                        <?php
                        $limit = $subscription['limits']['clients'];
                        if ($limit === -1) {
                            echo '<span class="text-green-600 font-medium">Unlimited</span>';
                        } else {
                            $percentage = ($usage['total_clients'] / $limit) * 100;
                            $color = $percentage >= 90 ? 'text-red-600' : ($percentage >= 70 ? 'text-yellow-600' : 'text-green-600');
                            echo "<span class='{$color} font-medium'>{$usage['total_clients']} / {$limit}</span>";
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- Team Members -->
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div class="w-8 h-8 bg-purple-500 rounded-md flex items-center justify-center">
                                <i class="fas fa-user-friends text-white text-sm"></i>
                            </div>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Team Members</dt>
                                <dd class="text-lg font-medium text-gray-900"><?= $usage['total_users'] ?></dd>
                            </dl>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-5 py-3">
                    <div class="text-sm">
                        <?php
                        $limit = $subscription['limits']['users'];
                        if ($limit === -1) {
                            echo '<span class="text-green-600 font-medium">Unlimited</span>';
                        } else {
                            $percentage = ($usage['total_users'] / $limit) * 100;
                            $color = $percentage >= 90 ? 'text-red-600' : ($percentage >= 70 ? 'text-yellow-600' : 'text-green-600');
                            echo "<span class='{$color} font-medium'>{$usage['total_users']} / {$limit}</span>";
                        }
                        ?>
                    </div>
                </div>
            </div>

            <!-- Revenue This Month -->
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <div class="w-8 h-8 bg-yellow-500 rounded-md flex items-center justify-center">
                                <i class="fas fa-dollar-sign text-white text-sm"></i>
                            </div>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">Revenue This Month</dt>
                                <dd class="text-lg font-medium text-gray-900">$0</dd>
                            </dl>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-5 py-3">
                    <div class="text-sm text-green-600 font-medium">
                        +0% from last month
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions & Recent Activity -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Quick Actions -->
            <div class="lg:col-span-1">
                <div class="bg-white shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">Quick Actions</h3>
                        <div class="space-y-3">
                            <a href="/proposals.php?action=create" 
                               class="w-full flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
                                <i class="fas fa-plus mr-2"></i> New Proposal
                            </a>
                            <a href="/invoices.php?action=create" 
                               class="w-full flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                                <i class="fas fa-file-invoice mr-2"></i> New Invoice
                            </a>
                            <a href="/clients.php?action=create" 
                               class="w-full flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                                <i class="fas fa-user-plus mr-2"></i> Add Client
                            </a>
                            <?php if (AuthManager::hasRole('super_admin') || AuthManager::hasRole('admin')): ?>
                            <a href="/team.php" 
                               class="w-full flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                                <i class="fas fa-users mr-2"></i> Manage Team
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Plan Upgrade Banner -->
                <?php if ($subscription['subscription_status'] === 'trial' || $subscription['plan_slug'] === 'starter'): ?>
                <div class="bg-white shadow rounded-lg mt-6">
                    <div class="px-4 py-5 sm:p-6">
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-2">Upgrade Your Plan</h3>
                        <p class="text-sm text-gray-600 mb-4">
                            Unlock more features and remove limitations with our Professional plan.
                        </p>
                        <a href="/billing.php?upgrade=1" 
                           class="w-full flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700">
                            <i class="fas fa-rocket mr-2"></i> Upgrade Now
                        </a>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Recent Activity -->
            <div class="lg:col-span-2">
                <div class="bg-white shadow rounded-lg">
                    <div class="px-4 py-5 sm:p-6">
                        <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">Recent Activity</h3>
                        
                        <?php if (empty($recentActivity)): ?>
                        <div class="text-center py-8">
                            <i class="fas fa-inbox text-gray-400 text-4xl mb-4"></i>
                            <p class="text-gray-500">No recent activity</p>
                            <p class="text-sm text-gray-400 mt-2">Start creating proposals and invoices to see them here.</p>
                        </div>
                        <?php else: ?>
                        <div class="flow-root">
                            <ul class="-mb-8">
                                <?php foreach ($recentActivity as $activity): ?>
                                <li>
                                    <div class="relative pb-8">
                                        <div class="relative flex space-x-3">
                                            <div>
                                                <span class="h-8 w-8 rounded-full flex items-center justify-center ring-8 ring-white
                                                    <?= $activity['type'] === 'proposal' ? 'bg-blue-500' : 'bg-green-500' ?>">
                                                    <i class="fas fa-<?= $activity['type'] === 'proposal' ? 'file-contract' : 'file-invoice' ?> text-white text-xs"></i>
                                                </span>
                                            </div>
                                            <div class="min-w-0 flex-1 justify-between space-y-4">
                                                <div>
                                                    <div class="text-sm">
                                                        <a href="/<?= $activity['type'] ?>s.php?action=view&id=<?= $activity['id'] ?>" 
                                                           class="font-medium text-gray-900">
                                                            <?= htmlspecialchars($activity['title']) ?>
                                                        </a>
                                                        <span class="ml-2 text-xs text-gray-500 uppercase">
                                                            <?= $activity['type'] ?>
                                                        </span>
                                                    </div>
                                                    <p class="mt-0.5 text-sm text-gray-500">
                                                        Created <?= date('M j, Y \a\t g:i A', strtotime($activity['created_at'])) ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleUserMenu() {
            const menu = document.getElementById('userMenu');
            menu.classList.toggle('hidden');
        }

        function switchWorkspace(companyId) {
            if (companyId !== '<?= $company['id'] ?>') {
                if (confirm('Switch to a different workspace?')) {
                    fetch('/api/switch-workspace.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ company_id: companyId })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            window.location.href = data.redirect_url;
                        }
                    });
                }
            }
        }

        // Close user menu when clicking outside
        document.addEventListener('click', function(event) {
            const userMenu = document.getElementById('userMenu');
            const userMenuButton = event.target.closest('button[onclick="toggleUserMenu()"]');
            
            if (!userMenuButton && !userMenu.contains(event.target)) {
                userMenu.classList.add('hidden');
            }
        });
    </script>
</body>
</html>
