<?php
session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

$userId = $_SESSION['user_id'];

// Get company
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];
$currency = $company['currency'];

// ---------- STATS ----------
// Total Clients
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM clients WHERE company_id = ?");
$stmt->execute([$companyId]);
$total_clients = $stmt->fetch()['total'];

// Total Invoices (all invoices, regardless of status)
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM documents WHERE company_id = ? AND type = 'invoice'");
$stmt->execute([$companyId]);
$total_invoices = $stmt->fetch()['total'];

// Total Revenue (sum of paid invoices)
$stmt = $pdo->prepare("SELECT SUM(total) as total FROM documents WHERE company_id = ? AND type = 'invoice' AND status = 'paid'");
$stmt->execute([$companyId]);
$total_revenue = $stmt->fetch()['total'] ?? 0;

// Unpaid Invoices (sent, partially_paid, overdue - not paid, not draft)
$stmt = $pdo->prepare("SELECT SUM(total) as total FROM documents WHERE company_id = ? AND type = 'invoice' AND status NOT IN ('paid', 'draft')");
$stmt->execute([$companyId]);
$total_unpaid = $stmt->fetch()['total'] ?? 0;

// ---------- RECENT DOCUMENTS (last 10) ----------
$stmt = $pdo->prepare("
    SELECT d.*, c.name as client_name 
    FROM documents d 
    LEFT JOIN clients c ON d.client_id = c.id 
    WHERE d.company_id = ? 
    ORDER BY d.created_at DESC 
    LIMIT 10
");
$stmt->execute([$companyId]);
$recent_documents = $stmt->fetchAll();

// ---------- CHART DATA (last 6 months revenue) ----------
$stmt = $pdo->prepare("
    SELECT 
        DATE_FORMAT(issue_date, '%Y-%m') as month_label,
        DATE_FORMAT(issue_date, '%M') as month_name,
        SUM(total) as revenue
    FROM documents
    WHERE company_id = ? 
        AND type = 'invoice' 
        AND status = 'paid'
        AND issue_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
    GROUP BY month_label, month_name
    ORDER BY month_label ASC
");
$stmt->execute([$companyId]);
$chart_rows = $stmt->fetchAll();

// Prepare arrays for Chart.js
$months = [];
$revenues = [];
foreach ($chart_rows as $row) {
    $months[] = $row['month_name'];
    $revenues[] = (float) $row['revenue'];
}
// If no data, show placeholder
if (empty($months)) {
    $months = ['No Data'];
    $revenues = [0];
}

include 'includes/header.php';
?>

<!-- Success/Error Messages (optional) -->
<?php if (isset($_SESSION['success'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
<?php endif; ?>

<!-- Stats Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-500 dark:text-gray-400 text-sm">Total Clients</p>
                <p class="text-3xl font-bold text-gray-800 dark:text-white"><?php echo $total_clients; ?></p>
            </div>
            <div class="w-12 h-12 bg-blue-100 dark:bg-blue-900/50 rounded-full flex items-center justify-center">
                <i class="fas fa-users text-blue-600 dark:text-blue-400 text-xl"></i>
            </div>
        </div>
    </div>
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-500 dark:text-gray-400 text-sm">Total Invoices</p>
                <p class="text-3xl font-bold text-gray-800 dark:text-white"><?php echo $total_invoices; ?></p>
            </div>
            <div class="w-12 h-12 bg-purple-100 dark:bg-purple-900/50 rounded-full flex items-center justify-center">
                <i class="fas fa-file-invoice text-purple-600 dark:text-purple-400 text-xl"></i>
            </div>
        </div>
    </div>
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-500 dark:text-gray-400 text-sm">Total Revenue</p>
                <p class="text-3xl font-bold text-gray-800 dark:text-white"><?php echo formatMoney($total_revenue, $currency); ?></p>
            </div>
            <div class="w-12 h-12 bg-green-100 dark:bg-green-900/50 rounded-full flex items-center justify-center">
                <i class="fas fa-chart-line text-green-600 dark:text-green-400 text-xl"></i>
            </div>
        </div>
    </div>
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 border border-gray-100 dark:border-gray-700">
        <div class="flex items-center justify-between">
            <div>
                <p class="text-gray-500 dark:text-gray-400 text-sm">Unpaid Invoices</p>
                <p class="text-3xl font-bold text-gray-800 dark:text-white"><?php echo formatMoney($total_unpaid, $currency); ?></p>
            </div>
            <div class="w-12 h-12 bg-red-100 dark:bg-red-900/50 rounded-full flex items-center justify-center">
                <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 text-xl"></i>
            </div>
        </div>
    </div>
</div>

<!-- Revenue Chart -->
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-8">
    <h3 class="text-lg font-semibold text-gray-800 dark:text-white mb-4">Revenue Overview (Last 6 Months)</h3>
    <canvas id="revenueChart" height="100"></canvas>
    <?php if (empty($chart_rows)): ?>
        <p class="text-center text-gray-500 mt-4">No paid invoices yet. Revenue chart will appear here once you have payments.</p>
    <?php endif; ?>
</div>

<!-- Recent Documents -->
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Recent Documents</h3>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-gray-50 dark:bg-gray-700/50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Number</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Type</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Client</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Amount</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Status</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                <?php if (empty($recent_documents)): ?>
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                            No documents found. <a href="document-form.php" class="text-blue-600">Create your first document</a>
                        </td>
                    </tr>
                <?php else: foreach ($recent_documents as $doc): ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white"><?php echo htmlspecialchars($doc['document_number']); ?></td>
                        <td class="px-6 py-4 text-sm capitalize"><?php echo $doc['type']; ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($doc['client_name'] ?? 'N/A'); ?></td>
                        <td class="px-6 py-4 text-sm font-semibold text-gray-700 dark:text-gray-300"><?php echo formatMoney($doc['total'], $doc['currency']); ?></td>
                        <td class="px-6 py-4"><?php echo getStatusBadge($doc['status']); ?></td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const ctx = document.getElementById('revenueChart').getContext('2d');
    const months = <?php echo json_encode($months); ?>;
    const revenues = <?php echo json_encode($revenues); ?>;
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: months,
            datasets: [{
                label: 'Revenue (<?php echo htmlspecialchars($currency); ?>)',
                data: revenues,
                borderColor: '#3B82F6',
                tension: 0.4,
                fill: true,
                backgroundColor: 'rgba(59, 130, 246, 0.1)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { position: 'top' },
                tooltip: { callbacks: { label: function(context) { return context.raw.toFixed(2); } } }
            },
            scales: {
                y: { beginAtZero: true, ticks: { callback: function(value) { return value.toFixed(2); } } }
            }
        }
    });
</script>

<?php include 'includes/footer.php'; ?>