<?php

class DashboardController
{
    private $pdo;
    private $auth;

    public function __construct($pdo)
    {
        $this->pdo  = $pdo;
        $this->auth = new Auth($pdo);
    }

    public function index($request)
    {
        try {
            $user = $this->auth->user();
            if (!$user) {
                header('Location: /login');
                exit;
            }

            // Prefer tenant from user, fallback to session
            $tenantId = (int)($user['tenant_id'] ?? ($_SESSION['tenant_id'] ?? 0));

            // Placeholder lead stats (can be expanded later)
            $stats = [
                'total_leads'      => 0,
                'new_leads'        => 0,
                'conversion_rate'  => 0,
                'avg_lead_score'   => 0,
            ];

            // Task KPIs
            $taskKpis = [
                'total'        => 0,
                'not_started'  => 0,
                'in_progress'  => 0,
                'completed'    => 0,
                'cancelled'    => 0,
            ];

            if ($tenantId > 0) {
                $sql = "
                    SELECT
                        COUNT(*) AS total,
                        SUM(status = 'not_started')                        AS not_started,
                        SUM(status IN ('started', 'in_progress'))          AS in_progress,
                        SUM(status = 'completed')                          AS completed,
                        SUM(status = 'cancelled')                          AS cancelled
                    FROM tasks
                    WHERE tenant_id = :tid
                ";

                $stmt = $this->pdo->prepare($sql);
                $stmt->execute([':tid' => $tenantId]);
                $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

                $taskKpis = [
                    'total'        => (int)($row['total']        ?? 0),
                    'not_started'  => (int)($row['not_started']  ?? 0),
                    'in_progress'  => (int)($row['in_progress']  ?? 0),
                    'completed'    => (int)($row['completed']    ?? 0),
                    'cancelled'    => (int)($row['cancelled']    ?? 0),
                ];
            }

            $view = new View();
            return $view->render('pages/dashboard', [
                'title'    => 'Dashboard',
                'stats'    => $stats,
                'taskKpis' => $taskKpis,
                'user'     => $user,
            ]);
        } catch (Exception $e) {
            error_log("Dashboard error: " . $e->getMessage());
            return "Error loading dashboard. Please try again.";
        }
    }
}
