<?php

class LeadsController extends BaseController
{
    protected $pdo;

    public function __construct($pdo = null)
    {
        parent::__construct();

        // Use the passed PDO or fall back to the shared Database connection
        $this->pdo = $pdo ?: Database::getConnection();
    }

    /**
     * Main leads listing page (with filters + stats for new dashboard UI)
     */
    public function index()
    {
        $this->authCheck();

        $tenantId = $_SESSION['tenant_id'];

        // Simple filters for the new UI
        $statusFilter = $_GET['status'] ?? null;
        $search       = trim($_GET['q'] ?? '');

        // Base WHERE clause
        $where  = ['l.tenant_id = :tenant_id'];
        $params = ['tenant_id' => $tenantId];

        // Optional status filter
        if (!empty($statusFilter) && $statusFilter !== 'all') {
            $where[]             = 'l.status = :status';
            $params['status']    = $statusFilter;
        }

        // Optional search across name / email / company
        if ($search !== '') {
            $where[]              = '(l.first_name LIKE :q 
                                   OR l.last_name LIKE :q 
                                   OR l.email LIKE :q 
                                   OR l.company LIKE :q)';
            $params['q'] = '%' . $search . '%';
        }

        $whereSql = implode(' AND ', $where);

        try {
            // Main leads list (for table)
            $sql = "
                SELECT l.*, 
                       CONCAT(l.first_name, ' ', l.last_name) AS full_name,
                       f.name AS form_name
                FROM leads l
                LEFT JOIN forms f ON l.form_id = f.id
                WHERE {$whereSql}
                ORDER BY l.created_at DESC
            ";
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Summary stats for cards (reuse getStats logic)
            $stats = $this->computeStats($tenantId);
        } catch (Exception $e) {
            error_log("Leads index error: " . $e->getMessage());
            $leads = [];
            $stats = [
                'total_leads'        => 0,
                'leads_today'        => 0,
                'high_priority_leads'=> 0,
                'converted_leads'    => 0,
            ];
        }

        $this->render('pages/leads/index', [
            'leads'       => $leads,
            'stats'       => $stats,
            'filters'     => [
                'status' => $statusFilter ?? 'all',
                'q'      => $search,
            ],
            'currentPage' => 'leads',
        ]);
    }

    /**
     * Lead detail page for new "Lead Overview / Behavior" view
     */
    public function show($leadId)
    {
        $this->authCheck();

        $lead = $this->getLeadById($leadId);
        if (!$lead) {
            $_SESSION['error'] = 'Lead not found';
            $this->redirect('/lead-management/public/app/leads');
        }

        // Build a simple timeline from known columns (no extra tables required)
        $timeline = [];

        if (!empty($lead['created_at'])) {
            $timeline[] = [
                'label' => 'Lead created',
                'type'  => 'created',
                'at'    => $lead['created_at'],
            ];
        }

        if (!empty($lead['updated_at']) && $lead['updated_at'] !== $lead['created_at']) {
            $timeline[] = [
                'label' => 'Last updated',
                'type'  => 'updated',
                'at'    => $lead['updated_at'],
            ];
        }

        if (!empty($lead['last_ai_scoring'])) {
            $timeline[] = [
                'label' => 'Last AI scoring',
                'type'  => 'ai_scoring',
                'at'    => $lead['last_ai_scoring'],
            ];
        }

        if (!empty($lead['last_email_generated'])) {
            $timeline[] = [
                'label' => 'Last AI email generated',
                'type'  => 'ai_email',
                'at'    => $lead['last_email_generated'],
            ];
        }

        // Sort timeline descending by date
        usort($timeline, function ($a, $b) {
            return strtotime($b['at']) <=> strtotime($a['at']);
        });

        $this->render('pages/leads/show', [
            'lead'        => $lead,
            'timeline'    => $timeline,
            'currentPage' => 'leads',
        ]);
    }

    /**
     * Show create lead form
     */
    public function create()
    {
        $this->authCheck();
        $this->render('pages/leads/form', [
            'lead'        => null,
            'currentPage' => 'leads',
        ]);
    }

    /**
     * Store new lead
     */
    public function store()
    {
        $this->authCheck();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Invalid request method';
            $this->redirect('/lead-management/public/app/leads/create');
        }

        $errors = $this->validateLeadData($_POST);

        if (!empty($errors)) {
            $_SESSION['error']     = implode('<br>', $errors);
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/leads/create');
        }

        try {
            $tenantId = $_SESSION['tenant_id'];

            $stmt = $this->pdo->prepare("
                INSERT INTO leads (
                    tenant_id, first_name, last_name, email, phone, company, 
                    industry, source, status, notes, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            $stmt->execute([
                $tenantId,
                trim($_POST['first_name']),
                trim($_POST['last_name'] ?? ''),
                trim($_POST['email'] ?? ''),
                trim($_POST['phone'] ?? ''),
                trim($_POST['company'] ?? ''),
                trim($_POST['industry'] ?? ''),
                $_POST['source'] ?? 'manual',
                $_POST['status'] ?? 'new',
                trim($_POST['notes'] ?? ''),
            ]);

            $leadId = $this->pdo->lastInsertId();

            // Auto-score with AI if enabled (button/checkbox in new UI)
            if (isset($_POST['auto_score']) && $_POST['auto_score'] === '1') {
                $this->scoreLead($leadId);
            }

            $_SESSION['success'] = 'Lead created successfully!';
            $this->redirect('/lead-management/public/app/leads');
        } catch (Exception $e) {
            error_log("Lead creation error: " . $e->getMessage());
            $_SESSION['error']     = 'Failed to create lead: ' . $e->getMessage();
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/leads/create');
        }
    }

    /**
     * Show edit lead form
     */
    public function edit($leadId)
    {
        $this->authCheck();
        $lead = $this->getLeadById($leadId);
        if (!$lead) {
            $_SESSION['error'] = 'Lead not found';
            $this->redirect('/lead-management/public/app/leads');
        }

        $this->render('pages/leads/form', [
            'lead'        => $lead,
            'currentPage' => 'leads',
        ]);
    }

    /**
     * Update lead
     */
    public function update($leadId)
    {
        $this->authCheck();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $_SESSION['error'] = 'Invalid request method';
            $this->redirect('/lead-management/public/app/leads/' . $leadId . '/edit');
        }

        $lead = $this->getLeadById($leadId);
        if (!$lead) {
            $_SESSION['error'] = 'Lead not found';
            $this->redirect('/lead-management/public/app/leads');
        }

        $errors = $this->validateLeadData($_POST, $leadId);

        if (!empty($errors)) {
            $_SESSION['error']     = implode('<br>', $errors);
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/leads/' . $leadId . '/edit');
        }

        try {
            $tenantId = $_SESSION['tenant_id'];
            $stmt = $this->pdo->prepare("
                UPDATE leads 
                SET first_name = ?, last_name = ?, email = ?, phone = ?, 
                    company = ?, industry = ?, source = ?, status = ?, notes = ?, 
                    updated_at = NOW()
                WHERE id = ? AND tenant_id = ?
            ");

            $stmt->execute([
                trim($_POST['first_name']),
                trim($_POST['last_name'] ?? ''),
                trim($_POST['email'] ?? ''),
                trim($_POST['phone'] ?? ''),
                trim($_POST['company'] ?? ''),
                trim($_POST['industry'] ?? ''),
                $_POST['source'] ?? 'manual',
                $_POST['status'] ?? 'new',
                trim($_POST['notes'] ?? ''),
                $leadId,
                $tenantId,
            ]);

            $_SESSION['success'] = 'Lead updated successfully!';
            $this->redirect('/lead-management/public/app/leads');
        } catch (Exception $e) {
            error_log("Lead update error: " . $e->getMessage());
            $_SESSION['error']     = 'Failed to update lead: ' . $e->getMessage();
            $_SESSION['form_data'] = $_POST;
            $this->redirect('/lead-management/public/app/leads/' . $leadId . '/edit');
        }
    }

    /**
     * Delete lead
     */
    public function delete($leadId)
    {
        $this->authCheck();
        $lead = $this->getLeadById($leadId);
        if (!$lead) {
            $_SESSION['error'] = 'Lead not found';
            $this->redirect('/lead-management/public/app/leads');
        }

        try {
            $tenantId = $_SESSION['tenant_id'];
            $stmt = $this->pdo->prepare("DELETE FROM leads WHERE id = ? AND tenant_id = ?");
            $stmt->execute([$leadId, $tenantId]);

            $_SESSION['success'] = 'Lead deleted successfully!';
        } catch (Exception $e) {
            error_log("Lead deletion error: " . $e->getMessage());
            $_SESSION['error'] = 'Failed to delete lead: ' . $e->getMessage();
        }

        $this->redirect('/lead-management/public/app/leads');
    }

    // ==================== AI METHODS ====================

    /**
     * Score a lead with AI (AJAX)
     */
    public function scoreLead($leadId)
    {
        $this->authCheck();
        $lead = $this->getLeadById($leadId);

        if (!$lead) {
            return $this->json(['success' => false, 'error' => 'Lead not found']);
        }

        try {
            $scoreResult = $this->aiService->scoreLead($lead);

            // Update lead with AI score
            $stmt = $this->pdo->prepare("
                UPDATE leads 
                SET ai_score = ?, ai_score_category = ?, ai_score_reasoning = ?, 
                    ai_confidence = ?, ai_model_used = ?, last_ai_scoring = NOW(), 
                    updated_at = NOW()
                WHERE id = ? AND tenant_id = ?
            ");

            $stmt->execute([
                $scoreResult['score']      ?? 0,
                $scoreResult['category']   ?? 'Cold',
                $scoreResult['reasoning']  ?? 'No reasoning provided',
                $scoreResult['confidence'] ?? 0.0,
                $scoreResult['ai_model']   ?? 'rule_based',
                $leadId,
                $_SESSION['tenant_id'],
            ]);

            return $this->json([
                'success' => true,
                'score'   => $scoreResult,
            ]);
        } catch (Exception $e) {
            error_log("AI scoring error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Generate email for lead (AJAX)
     */
    public function generateEmail($leadId)
    {
        $this->authCheck();
        $lead = $this->getLeadById($leadId);

        if (!$lead) {
            return $this->json(['success' => false, 'error' => 'Lead not found']);
        }

        try {
            $input     = json_decode(file_get_contents('php://input'), true) ?: [];
            $emailType = $input['email_type'] ?? 'follow_up';

            $emailResult = $this->aiService->generateEmailContent($lead, $emailType);

            // Update lead with email generation info
            $stmt = $this->pdo->prepare("
                UPDATE leads 
                SET last_email_generated = NOW(), 
                    email_generation_count = COALESCE(email_generation_count, 0) + 1,
                    updated_at = NOW()
                WHERE id = ? AND tenant_id = ?
            ");

            $stmt->execute([$leadId, $_SESSION['tenant_id']]);

            return $this->json([
                'success'       => true,
                'email_content' => $emailResult,
            ]);
        } catch (Exception $e) {
            error_log("Email generation error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Analyze lead behavior (AJAX)
     */
    public function analyzeBehavior($leadId)
    {
        $this->authCheck();
        $lead = $this->getLeadById($leadId);

        if (!$lead) {
            return $this->json(['success' => false, 'error' => 'Lead not found']);
        }

        try {
            $analysis = $this->aiService->analyzeLeadBehavior($lead);

            return $this->json([
                'success'  => true,
                'analysis' => $analysis,
            ]);
        } catch (Exception $e) {
            error_log("Behavior analysis error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    // ==================== HELPER METHODS ====================

    /**
     * Validate lead data
     */
    private function validateLeadData($data, $leadId = null)
    {
        $errors = [];

        if (empty(trim($data['first_name'] ?? ''))) {
            $errors[] = 'First name is required';
        }

        if (!empty($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Invalid email format';
        }

        // Check for duplicate email
        if (!empty($data['email'])) {
            $tenantId = $_SESSION['tenant_id'];
            $sql      = "SELECT id FROM leads WHERE email = ? AND tenant_id = ?";
            $params   = [trim($data['email']), $tenantId];

            if ($leadId) {
                $sql     .= " AND id != ?";
                $params[] = $leadId;
            }

            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);

            if ($stmt->fetch()) {
                $errors[] = 'A lead with this email already exists';
            }
        }

        return $errors;
    }

    /**
     * Get lead by ID (with tenant check)
     */
    private function getLeadById($leadId)
    {
        try {
            $tenantId = $_SESSION['tenant_id'];
            $stmt = $this->pdo->prepare("
                SELECT l.*, 
                       CONCAT(l.first_name, ' ', l.last_name) AS full_name,
                       f.name AS form_name
                FROM leads l 
                LEFT JOIN forms f ON l.form_id = f.id 
                WHERE l.id = ? AND l.tenant_id = ?
            ");
            $stmt->execute([$leadId, $tenantId]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            error_log("Get lead by ID error: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Internal: compute stats used both by dashboard and leads page
     */
    private function computeStats($tenantId)
    {
        $stats = [
            'total_leads'         => 0,
            'leads_today'         => 0,
            'high_priority_leads' => 0,
            'converted_leads'     => 0,
        ];

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

            // New 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 priority leads (ai_score >= 80)
            $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM leads WHERE tenant_id = ? AND ai_score >= 80");
            $stmt->execute([$tenantId]);
            $stats['high_priority_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();
        } catch (Exception $e) {
            error_log("Stats compute error: " . $e->getMessage());
        }

        return $stats;
    }

    /**
     * JSON stats endpoint (if you want to call it from JS)
     */
    public function getStats()
    {
        $this->authCheck();
        $tenantId = $_SESSION['tenant_id'];

        try {
            $stats = $this->computeStats($tenantId);
            return $this->json(['success' => true, 'stats' => $stats]);
        } catch (Exception $e) {
            error_log("Stats error: " . $e->getMessage());
            return $this->json(['success' => false, 'error' => $e->getMessage()]);
        }
    }
}
