<?php

// No namespace – consistent with the rest of the app

class AnalyticsController extends BaseController
{
    protected $pdo;

    public function __construct($pdo = null)
    {
        parent::__construct();
        $this->pdo = $pdo ?: Database::getConnection();
    }

    /**
     * Global analytics dashboard
     */
    public function index()
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];

        // Default structures so view never explodes
        $stats = [
            'total_leads'        => 0,
            'leads_today'        => 0,
            'high_score_leads'   => 0,
            'converted_leads'    => 0,
            'total_forms'        => 0,
            'total_submissions'  => 0,
        ];

        $trends         = [];
        $formsOverview  = [];
        $recentActivity = [];
        $conversion     = [
            'total_leads'      => 0,
            'converted_leads'  => 0,
            'qualified_leads'  => 0,
            'avg_ai_score'     => null,
        ];

        try {
            // ====== High-level stats ======
            // Total leads
            $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM leads WHERE tenant_id = ?");
            $stmt->execute([$tenantId]);
            $stats['total_leads'] = (int)$stmt->fetchColumn();

            // Leads today
            $stmt = $this->pdo->prepare("
                SELECT COUNT(*) 
                FROM leads 
                WHERE tenant_id = ? AND DATE(created_at) = CURDATE()
            ");
            $stmt->execute([$tenantId]);
            $stats['leads_today'] = (int)$stmt->fetchColumn();

            // High score leads (>= 80)
            $stmt = $this->pdo->prepare("
                SELECT COUNT(*) 
                FROM leads 
                WHERE tenant_id = ? AND ai_score >= 80
            ");
            $stmt->execute([$tenantId]);
            $stats['high_score_leads'] = (int)$stmt->fetchColumn();

            // Converted leads
            $stmt = $this->pdo->prepare("
                SELECT COUNT(*) 
                FROM leads 
                WHERE tenant_id = ? AND status = 'converted'
            ");
            $stmt->execute([$tenantId]);
            $stats['converted_leads'] = (int)$stmt->fetchColumn();

            // Total forms
            $stmt = $this->pdo->prepare("
                SELECT COUNT(*) 
                FROM forms 
                WHERE tenant_id = ?
            ");
            $stmt->execute([$tenantId]);
            $stats['total_forms'] = (int)$stmt->fetchColumn();

            // Total submissions
            $stmt = $this->pdo->prepare("
                SELECT COUNT(*) 
                FROM form_submissions 
                WHERE tenant_id = ?
            ");
            $stmt->execute([$tenantId]);
            $stats['total_submissions'] = (int)$stmt->fetchColumn();

            // ====== Trends: submissions last 14 days ======
            $stmt = $this->pdo->prepare("
                SELECT 
                    DATE(created_at) AS date,
                    COUNT(*)         AS submissions
                FROM form_submissions
                WHERE tenant_id = ?
                  AND created_at >= DATE_SUB(NOW(), INTERVAL 14 DAY)
                GROUP BY DATE(created_at)
                ORDER BY date ASC
            ");
            $stmt->execute([$tenantId]);
            $trends = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // ====== Forms overview: submissions per form ======
            $stmt = $this->pdo->prepare("
                SELECT 
                    f.id,
                    f.name,
                    COUNT(fs.id) AS submissions
                FROM forms f
                LEFT JOIN form_submissions fs
                    ON fs.form_id = f.id
                   AND fs.tenant_id = ?
                WHERE f.tenant_id = ?
                GROUP BY f.id, f.name
                ORDER BY submissions DESC, f.created_at DESC
            ");
            $stmt->execute([$tenantId, $tenantId]);
            $formsOverview = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // ====== Recent activity: last 10 submissions ======
            $stmt = $this->pdo->prepare("
                SELECT 
                    fs.id,
                    fs.form_id,
                    fs.lead_id,
                    fs.created_at,
                    f.name AS form_name,
                    l.first_name,
                    l.last_name,
                    l.email
                FROM form_submissions fs
                LEFT JOIN forms f    ON fs.form_id = f.id
                LEFT JOIN leads l    ON fs.lead_id = l.id
                WHERE fs.tenant_id = ?
                ORDER BY fs.created_at DESC
                LIMIT 10
            ");
            $stmt->execute([$tenantId]);
            $recentActivity = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // ====== Conversion stats from leads ======
            $stmt = $this->pdo->prepare("
                SELECT 
                    COUNT(*) AS total_leads,
                    COUNT(CASE WHEN status = 'converted' THEN 1 END) AS converted_leads,
                    COUNT(CASE WHEN status = 'qualified' THEN 1 END) AS qualified_leads,
                    AVG(ai_score) AS avg_ai_score
                FROM leads
                WHERE tenant_id = ?
            ");
            $stmt->execute([$tenantId]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                $conversion = [
                    'total_leads'      => (int)($row['total_leads'] ?? 0),
                    'converted_leads'  => (int)($row['converted_leads'] ?? 0),
                    'qualified_leads'  => (int)($row['qualified_leads'] ?? 0),
                    'avg_ai_score'     => isset($row['avg_ai_score']) ? round((float)$row['avg_ai_score'], 1) : null,
                ];
            }
        } catch (Exception $e) {
            error_log("AnalyticsController@index error: " . $e->getMessage());
            // Fail gracefully; view will just show zeros/empty shells
        }

        return $this->render('pages/analytics', [
            'stats'          => $stats,
            'trends'         => $trends,
            'formsOverview'  => $formsOverview,
            'recentActivity' => $recentActivity,
            'conversion'     => $conversion,
            'currentPage'    => 'analytics',
        ]);
    }

    /**
     * AI tools hub (SkyBlue page wired to /app/ai-tools)
     */
    public function aiTools()
    {
        $this->authCheck();

        return $this->render('pages/ai-tools', [
            'currentPage' => 'ai-tools',
        ]);
    }
}
