<?php

declare(strict_types=1);

namespace App\Controllers;

use Exception;

/**
 * Controller do Painel de Revendas
 * Gerencia dashboard e funcionalidades para revendedores
 */
class RevendaController extends BaseController
{
    /**
     * Exibe formulário de login para revendedores
     */
    public function showLogin(): void
    {
        // Se já está logado, redireciona para o dashboard
        if ($this->session->isAuthenticated() && $this->session->get('user_type') === 'revenda') {
            $this->redirect('revenda/dashboard');
            return;
        }

        $this->view('revenda/login', [
            'pageTitle' => 'Login Revenda',
            'activeMenu' => 'revenda'
        ]);
    }

    /**
     * Processa login de revendedor
     */
    public function login(): void
    {
        // Suporta tanto JSON quanto form data
        $data = $this->request->isJson() ? $this->request->json() : $this->request->all();

        $email = $data['email'] ?? '';
        $password = $data['password'] ?? '';

        if (empty($email) || empty($password)) {
            $this->error('Email e senha são obrigatórios');
            return;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error('Email inválido');
            return;
        }

        if (strlen($password) < 6) {
            $this->error('Senha deve ter no mínimo 6 caracteres');
            return;
        }

        try {
            // Para demonstração, aceita credenciais específicas
            if ($email === 'revenda@demo.com' && $password === 'demo123') {
                // Simular sessão de revendedor
                $this->session->set('authenticated', true);
                $this->session->set('user_id', 999);
                $this->session->set('user_type', 'revenda');
                $this->session->set('user_name', 'Revendedor Demo');
                $this->session->set('user_email', $email);

                $this->success('Login realizado com sucesso!', [
                    'redirect' => '../revenda/dashboard'
                ]);
                return;
            }

            // Em produção, aqui seria a validação real no banco
            $this->error('Email ou senha incorretos');

        } catch (Exception $e) {
            error_log("Erro no login de revenda: " . $e->getMessage());
            $this->error('Erro interno do servidor');
        }
    }

    /**
     * Logout do painel de revendas
     */
    public function logout(): void
    {
        $this->session->destroy();
        $this->redirect('revenda/login');
    }

    /**
     * Exibe o painel principal de revendas
     */
    public function index(): void
    {
        try {
            // Verifica se está autenticado como revendedor
            if (!$this->session->isAuthenticated() || $this->session->get('user_type') !== 'revenda') {
                $this->redirect('revenda/login');
                return;
            }

            // Se não há conexão com banco, exibe dados de demonstração
            if (!$this->db) {
                $this->view('revenda/dashboard', [
                    'stats' => $this->getDemoStats(),
                    'clientesRecentes' => $this->getDemoClientes(),
                    'vendasRecentes' => $this->getDemoVendas(),
                    'comissoes' => $this->getDemoComissoes(),
                    'pageTitle' => 'Painel de Revendas - Demonstração',
                    'activeMenu' => 'revenda',
                    'isDemo' => true,
                    'user' => [
                        'name' => $this->session->get('user_name', 'Revendedor Demo'),
                        'email' => $this->session->get('user_email', 'revenda@demo.com')
                    ]
                ]);
                return;
            }

            // Busca estatísticas gerais
            $stats = $this->getRevendaStats();

            // Busca clientes recentes
            $clientesRecentes = $this->getClientesRecentes();

            // Busca vendas recentes
            $vendasRecentes = $this->getVendasRecentes();

            // Busca comissões
            $comissoes = $this->getComissoes();

            $this->view('revenda/dashboard', [
                'stats' => $stats,
                'clientesRecentes' => $clientesRecentes,
                'vendasRecentes' => $vendasRecentes,
                'comissoes' => $comissoes,
                'pageTitle' => 'Painel de Revendas',
                'activeMenu' => 'revenda',
                'isDemo' => false
            ]);

        } catch (Exception $e) {
            error_log("Erro ao carregar painel de revendas: " . $e->getMessage());
            $this->error('Erro ao carregar painel de revendas');
        }
    }

    /**
     * Exibe relatório de comissões
     */
    public function comissoes(): void
    {
        try {
            $periodo = $this->request->get('periodo', 'mes_atual');
            $comissoes = $this->getComissoesDetalhadas($periodo);

            $this->view('revenda/comissoes', [
                'comissoes' => $comissoes,
                'periodo' => $periodo,
                'pageTitle' => 'Comissões',
                'activeMenu' => 'revenda'
            ]);

        } catch (Exception $e) {
            error_log("Erro ao carregar comissões: " . $e->getMessage());
            $this->error('Erro ao carregar comissões');
        }
    }

    /**
     * Exibe relatório de clientes
     */
    public function clientes(): void
    {
        try {
            $clientes = $this->getTodosClientes();

            $this->view('revenda/clientes', [
                'clientes' => $clientes,
                'pageTitle' => 'Meus Clientes',
                'activeMenu' => 'revenda'
            ]);

        } catch (Exception $e) {
            error_log("Erro ao carregar clientes: " . $e->getMessage());
            $this->error('Erro ao carregar clientes');
        }
    }

    /**
     * Exibe relatório de vendas
     */
    public function vendas(): void
    {
        try {
            $periodo = $this->request->get('periodo', 'mes_atual');
            $vendas = $this->getVendasDetalhadas($periodo);

            $this->view('revenda/vendas', [
                'vendas' => $vendas,
                'periodo' => $periodo,
                'pageTitle' => 'Minhas Vendas',
                'activeMenu' => 'revenda'
            ]);

        } catch (Exception $e) {
            error_log("Erro ao carregar vendas: " . $e->getMessage());
            $this->error('Erro ao carregar vendas');
        }
    }

    /**
     * Busca estatísticas gerais de revenda
     */
    private function getRevendaStats(): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        // Total de clientes
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as total
            FROM pessoas
            WHERE company_id = :company_id
            AND created_by = :user_id
            AND type = 'cliente'
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);
        $totalClientes = $stmt->fetch()['total'];

        // Total de vendas do mês
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as total, SUM(total) as valor_total
            FROM vendas
            WHERE company_id = :company_id
            AND created_by = :user_id
            AND DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);
        $vendasMes = $stmt->fetch();

        // Total de comissões do mês
        $stmt = $this->db->prepare("
            SELECT SUM(comissao) as total
            FROM vendas
            WHERE company_id = :company_id
            AND created_by = :user_id
            AND DATE_FORMAT(created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);
        $comissoesMes = $stmt->fetch()['total'] ?? 0;

        // Meta do mês (pode ser configurada)
        $metaMes = 50000; // Valor padrão, pode vir de configuração

        return [
            'totalClientes' => $totalClientes,
            'vendasMes' => $vendasMes['total'] ?? 0,
            'valorVendasMes' => $vendasMes['valor_total'] ?? 0,
            'comissoesMes' => $comissoesMes,
            'metaMes' => $metaMes,
            'percentualMeta' => $metaMes > 0 ? ($vendasMes['valor_total'] ?? 0) / $metaMes * 100 : 0
        ];
    }

    /**
     * Busca clientes recentes
     */
    private function getClientesRecentes(): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $stmt = $this->db->prepare("
            SELECT p.*,
                   COUNT(v.id) as total_vendas,
                   SUM(v.total) as valor_total_vendas
            FROM pessoas p
            LEFT JOIN vendas v ON p.id = v.customer_id
            WHERE p.company_id = :company_id
            AND p.created_by = :user_id
            AND p.type = 'cliente'
            GROUP BY p.id
            ORDER BY p.created_at DESC
            LIMIT 10
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Busca vendas recentes
     */
    private function getVendasRecentes(): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $stmt = $this->db->prepare("
            SELECT v.*, p.name as cliente_nome
            FROM vendas v
            LEFT JOIN pessoas p ON v.customer_id = p.id
            WHERE v.company_id = :company_id
            AND v.created_by = :user_id
            ORDER BY v.created_at DESC
            LIMIT 10
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Busca comissões do mês
     */
    private function getComissoes(): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $stmt = $this->db->prepare("
            SELECT
                DATE_FORMAT(created_at, '%Y-%m') as periodo,
                COUNT(*) as total_vendas,
                SUM(total) as valor_total,
                SUM(comissao) as comissao_total
            FROM vendas
            WHERE company_id = :company_id
            AND created_by = :user_id
            AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
            GROUP BY DATE_FORMAT(created_at, '%Y-%m')
            ORDER BY periodo DESC
            LIMIT 6
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Busca comissões detalhadas por período
     */
    private function getComissoesDetalhadas(string $periodo): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $whereClause = $this->getPeriodoWhereClause($periodo);

        $stmt = $this->db->prepare("
            SELECT v.*, p.name as cliente_nome
            FROM vendas v
            LEFT JOIN pessoas p ON v.customer_id = p.id
            WHERE v.company_id = :company_id
            AND v.created_by = :user_id
            $whereClause
            ORDER BY v.created_at DESC
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Busca todos os clientes do revendedor
     */
    private function getTodosClientes(): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $stmt = $this->db->prepare("
            SELECT p.*,
                   COUNT(v.id) as total_vendas,
                   SUM(v.total) as valor_total_vendas,
                   SUM(v.comissao) as total_comissoes,
                   MAX(v.created_at) as ultima_venda
            FROM pessoas p
            LEFT JOIN vendas v ON p.id = v.customer_id
            WHERE p.company_id = :company_id
            AND p.created_by = :user_id
            AND p.type = 'cliente'
            GROUP BY p.id
            ORDER BY p.name ASC
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Busca vendas detalhadas por período
     */
    private function getVendasDetalhadas(string $periodo): array
    {
        $companyId = $this->getCompanyId();
        $userId = $this->session->get('user_id');

        $whereClause = $this->getPeriodoWhereClause($periodo);

        $stmt = $this->db->prepare("
            SELECT v.*, p.name as cliente_nome
            FROM vendas v
            LEFT JOIN pessoas p ON v.customer_id = p.id
            WHERE v.company_id = :company_id
            AND v.created_by = :user_id
            $whereClause
            ORDER BY v.created_at DESC
        ");
        $stmt->execute(['company_id' => $companyId, 'user_id' => $userId]);

        return $stmt->fetchAll();
    }

    /**
     * Retorna cláusula WHERE baseada no período
     */
    private function getPeriodoWhereClause(string $periodo): string
    {
        switch ($periodo) {
            case 'hoje':
                return "AND DATE(v.created_at) = CURDATE()";
            case 'semana':
                return "AND v.created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK)";
            case 'mes_atual':
                return "AND DATE_FORMAT(v.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')";
            case 'mes_anterior':
                return "AND DATE_FORMAT(v.created_at, '%Y-%m') = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m')";
            case 'ano_atual':
                return "AND YEAR(v.created_at) = YEAR(NOW())";
            default:
                return "AND DATE_FORMAT(v.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')";
        }
    }

    /**
     * Dados de demonstração para o painel
     */
    private function getDemoStats(): array
    {
        return [
            'totalClientes' => 47,
            'vendasMes' => 23,
            'valorVendasMes' => 125430.50,
            'comissoesMes' => 12543.05,
            'metaMes' => 150000,
            'percentualMeta' => 83.6
        ];
    }

    private function getDemoClientes(): array
    {
        return [
            [
                'id' => 1,
                'name' => 'João Silva',
                'created_at' => '2025-01-10 14:30:00',
                'total_vendas' => 5,
                'valor_total_vendas' => 15430.00
            ],
            [
                'id' => 2,
                'name' => 'Maria Santos',
                'created_at' => '2025-01-09 10:15:00',
                'total_vendas' => 3,
                'valor_total_vendas' => 8750.00
            ],
            [
                'id' => 3,
                'name' => 'Pedro Costa',
                'created_at' => '2025-01-08 16:45:00',
                'total_vendas' => 7,
                'valor_total_vendas' => 22300.00
            ],
            [
                'id' => 4,
                'name' => 'Ana Oliveira',
                'created_at' => '2025-01-07 09:20:00',
                'total_vendas' => 2,
                'valor_total_vendas' => 5400.00
            ],
            [
                'id' => 5,
                'name' => 'Carlos Ferreira',
                'created_at' => '2025-01-06 13:10:00',
                'total_vendas' => 4,
                'valor_total_vendas' => 12350.00
            ]
        ];
    }

    private function getDemoVendas(): array
    {
        return [
            [
                'id' => 1001,
                'cliente_nome' => 'João Silva',
                'total' => 2450.00,
                'comissao' => 245.00,
                'created_at' => '2025-01-14 15:30:00'
            ],
            [
                'id' => 1002,
                'cliente_nome' => 'Maria Santos',
                'total' => 1870.00,
                'comissao' => 187.00,
                'created_at' => '2025-01-14 11:20:00'
            ],
            [
                'id' => 1003,
                'cliente_nome' => 'Pedro Costa',
                'total' => 3200.00,
                'comissao' => 320.00,
                'created_at' => '2025-01-13 16:45:00'
            ],
            [
                'id' => 1004,
                'cliente_nome' => 'Ana Oliveira',
                'total' => 1450.00,
                'comissao' => 145.00,
                'created_at' => '2025-01-13 09:15:00'
            ],
            [
                'id' => 1005,
                'cliente_nome' => 'Carlos Ferreira',
                'total' => 2890.00,
                'comissao' => 289.00,
                'created_at' => '2025-01-12 14:20:00'
            ]
        ];
    }

    private function getDemoComissoes(): array
    {
        return [
            [
                'periodo' => '2025-01',
                'total_vendas' => 23,
                'valor_total' => 125430.50,
                'comissao_total' => 12543.05
            ],
            [
                'periodo' => '2024-12',
                'total_vendas' => 31,
                'valor_total' => 156780.00,
                'comissao_total' => 15678.00
            ],
            [
                'periodo' => '2024-11',
                'total_vendas' => 28,
                'valor_total' => 134500.00,
                'comissao_total' => 13450.00
            ],
            [
                'periodo' => '2024-10',
                'total_vendas' => 25,
                'valor_total' => 118900.00,
                'comissao_total' => 11890.00
            ],
            [
                'periodo' => '2024-09',
                'total_vendas' => 22,
                'valor_total' => 98750.00,
                'comissao_total' => 9875.00
            ],
            [
                'periodo' => '2024-08',
                'total_vendas' => 19,
                'valor_total' => 87650.00,
                'comissao_total' => 8765.00
            ]
        ];
    }
}
