<?php 
    use Dompdf\Dompdf;
    use Dompdf\Options;

    class Creative extends Core  {

        const WEEKDAYS = [
            'monday'    => 'segunda',
            'tuesday'   => 'terça',
            'wednesday' => 'quarta',
            'thursday'  => 'quinta',
            'friday'    => 'sexta',
            'saturday'  => 'sábado',
            'sunday'    => 'domingo'
        ];

        function create() {
            $company_id = $_GET['company_id'];
            $process_id = $_GET['process_id'];
            $user_id    = isset($_GET['userId']) ? $_GET['userId'] : null;			
            $sql = "SELECT PL.*, C.*, C.district as bairro, PL.district as bairro1 FROM process_list AS PL
                    LEFT JOIN companies AS C ON C.id = PL.company
                    WHERE PL.id = :id AND PL.company = :company";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                'company' => $company_id,
                'id' => $process_id
            ]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            $options = new Options();
            $options->set('isRemoteEnabled', true); 
            $dompdf = new Dompdf($options);
            $daysList = array_map('trim', explode(',', strtolower($result['daysWeek'])));
            $firstDay = $daysList[0];
            $lastDay = $daysList[count($daysList) - 1];
            
            $firstDayLabel = Creative::WEEKDAYS[$firstDay] ?? '';
            $lastDayLabel  = Creative::WEEKDAYS[$lastDay] ?? '';
            
            // Pegando apenas as horas, ignorando os minutos
            list($hourStart, $minuteStart) = explode(':', $result['start_monday']);
            list($hourEnd, $minuteEnd) = explode(':', $result['end_monday']);
            
            $start_hour = $hourStart . ':' . $minuteStart;
            $end_hour   = $hourEnd . ':' . $minuteEnd;
            //$textoPeriodo = "De {$firstDayLabel} a {$lastDayLabel}, das {$start_hour} às {$end_hour}";
            $textoPeriodo = "Horário das {$start_hour} às {$end_hour}";
            
            $title = trim($result['sinonimo']);
            $salary = trim($result['salary']);
            $description = trim($result['creative_key']);
            
            if(empty($description)){
                $requirements = $result['requirements'];
                
                $url = 'https://app2.memprega.com.br/api/index.php?action=ai-generator:creative';

                $data = ['requirements' => $requirements, 'process_id' => $result['process_id'], 'sinonimo' => $result['sinonimo'] ];
                
                $options = [
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => http_build_query($data),
                ];
                
                $ch = curl_init();
                curl_setopt_array($ch, $options);
                
                $response = curl_exec($ch);
                curl_close($ch);
                $response = json_decode($response, true);
                $description = $response['text'];
            }
            
            $partes = $this->dividirDescricao($description);
            
            // Se veio só uma parte, escreve só ela
            if (count($partes) == 1) {
                $description = $partes[0];
            } else {
                // Primeira linha
                $description = $partes[0];
                // Segunda linha
                $description1 = $partes[1];
            } 
            
            $descricaoExtra = '';
            if (!empty($description1)) {
                $descricaoExtra = '<h3>' . trim($description1) . '</h3>';
            }
            
            $textdescription = '';
            if(!empty($description)){
                $textdescription = '<div class="p-absolute" style="top: 700px;">
                            <h2>Descrição</h2>
                            <h3>'.$textoPeriodo.'</h3>
                            <h3>'.$description.'</h3>
                            '.$descricaoExtra.'
                        </div>';
            }
            
            
            $address = "";
            if(!empty($result['state'])){
                if($result['state'] == 'undefined'){
                    $address = "";
                }else{
                    $address =  "{$result['bairro1']} - {$result['city']} / {$result['state']}";
                }
            }else{
                if($result['companystate'] == 'undefined'){
                    $address = "";
                }else{
                    $address =  "{$result['bairro']} - {$result['companycity']} / {$result['companystate']}";
                }
            }
            
            $localizacao = '';
            if(!empty($address)){
            $localizacao = '<div class="p-absolute" style="top: 550px;">
                            <h2>Localização</h2>
                            <h3>'. $address .'</h3>
                        </div>';
            }

            $html = '
                <!DOCTYPE html>
                <html>
                <head>
                    <link href="https://fonts.googleapis.com/css2?family=Cabin&display=swap" rel="stylesheet">
                    <style>
                        body { 
                            font-family: "Cabin", sans-serif;
                            background-color: #1e005a;
                            margin: 0;
                            padding: 0;
                        }
                        .img-container { 
                            position: relative;
                            width: 100%;
                            height: 100%;
                        }
                        .img-container img {
                            position: absolute;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                            height: 100%;
                            width: auto;
                        }
                        .p-absolute {
                            position: absolute;
                            left: 50%;
                            transform: translateX(-50%);
                            width: 80%;
                            text-align: center;
                        }
                        h2 {
                            color: #ffa33f;
                            margin: 0;
                        }
                        h3 {
                            color: white;
                            margin: 0;
                        }
                    </style>
                </head>
                <body>                    
                    <div class="img-container">
                        <img src="https://app2.memprega.com.br/api/assets/images/creative.png">
                        
                        <div class="p-absolute" style="top: 460px;">
                            <h2>'. $title .'</h2>
                        </div>
            
                        '.$localizacao.'
            
                        <div class="p-absolute" style="top: 610px;">
                            <h2>Informações</h2>
                            <h3>'.$this->formatSalary($salary).'</h3>
                            <h3>'. trim($result['workregime']) . ' | ' . trim($result['modalityjob']) .'</h3>
                        </div>
            
                        '.$textdescription.'
                    </div>
                </body>
                </html>
            ';
            
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream("creative.pdf", ["Attachment" => false]);
            
            if($user_id) {
                include_once __dir__ .  '/../core/LogEvent.php';
                $title = "Gerou criativo em PDF";
                $url = "/recruiter/process";           
            
                LogEvent::log($user_id, $process_id, $url, $title, LogEvent::CREATIVE_SHARE_PDF);
            }            
        }
        
        // 🔧 Função auxiliar para centralizar texto
        private function centerText($image, $text, $font, $fontSize, $y, $color, $imageWidth) {
            $bbox = imagettfbbox($fontSize, 0, $font, $text);
            $textWidth = $bbox[2] - $bbox[0];
            $x = ($imageWidth - $textWidth) / 2;
            imagettftext($image, $fontSize, 0, (int)$x, (int)$y, $color, $font, $text);
        }
        
        private function formatSalary($salary) {
            // Remove espaços e valida
            $salary = trim($salary);
            
            if (empty($salary) || $salary == '0' || $salary == '0,00' || $salary == '00,00' || $salary == '0000') {
                return 'salário a combinar';
            }
        
            // Remove tudo que não é número ou vírgula
            $salary = preg_replace('/[^\d,\.]/', '', $salary);
        
            // Se houver mais de uma vírgula ou ponto, vamos tentar padronizar:
            // 1. Trocar pontos por vazio (remover separadores de milhar)
            // 2. Trocar vírgula por ponto (para converter corretamente com floatval)
            $salary = str_replace('.', '', $salary);       // remove separadores de milhar
            $salary = str_replace(',', '', $salary);      // transforma vírgula decimal em ponto
        
            // Converte para float
            $valor = floatval($salary)/100;
        
            if ($valor == 0) {
                return 'salário a combinar';
            }
        
            // Retorna formatado no padrão brasileiro
            return 'R$ ' . number_format($valor, 2, ',', '.');
        }

        // private function dividirDescricao($descricao, $limite = 60) {
        //     $descricao = trim($descricao);
        
        //     // Se for menor ou igual ao limite, retorna como uma linha só
        //     if (mb_strlen($descricao) <= $limite) {
        //         return [$descricao];
        //     }
        
        //     // Pega a substring até o limite para buscar a última vírgula antes dele
        //     $parteAteLimite = mb_substr($descricao, 0, $limite);
        
        //     // Procura a última vírgula antes do limite
        //     $posVirgula = mb_strrpos($parteAteLimite, ',');
        
        //     if ($posVirgula !== false) {
        //         // Quebra na última vírgula antes do limite
        //         $parte1 = trim(mb_substr($descricao, 0, $posVirgula + 1)); // inclui a vírgula
        //         $parte2 = trim(mb_substr($descricao, $posVirgula + 1));
        //     } else {
        //         // Se não encontrou vírgula antes do limite, quebra no limite bruto
        //         $parte1 = trim(mb_substr($descricao, 0, $limite));
        //         $parte2 = trim(mb_substr($descricao, $limite));
        //     }
        
        //     return [$parte1, $parte2];
        // }
        
        private function dividirDescricao($descricao, $limite = 60) {
            $descricao = trim($descricao);
        
            // Usa wordwrap para quebrar respeitando palavras e vírgulas
            $quebrado = wordwrap($descricao, $limite, "\n", false);
        
            // Transforma cada linha em um item do array
            return explode("\n", $quebrado);
        }
        
        private function centerMultilineText($image, $text, $font, $fontSize, $y, $color, $maxWidth, $lineSpacing = 10) {
            // Quebra a string automaticamente
            $words = explode(' ', $text);
            $lines = [];
            $currentLine = '';
        
            foreach ($words as $word) {
                $testLine = $currentLine ? "$currentLine $word" : $word;
                $bbox = imagettfbbox($fontSize, 0, $font, $testLine);
                $lineWidth = $bbox[2] - $bbox[0];
        
                if ($lineWidth > $maxWidth && $currentLine) {
                    $lines[] = $currentLine;
                    $currentLine = $word;
                } else {
                    $currentLine = $testLine;
                }
            }
            if ($currentLine) {
                $lines[] = $currentLine;
            }
        
            // Desenha linha por linha centralizada
            $imageHeight = imagesy($image);
            $totalHeight = count($lines) * ($fontSize + $lineSpacing);
            $startY = $y - ($totalHeight / 2);
        
            foreach ($lines as $line) {
                $bbox = imagettfbbox($fontSize, 0, $font, $line);
                $textWidth = $bbox[2] - $bbox[0];
                $x = ($maxWidth - $textWidth) / 2;
                imagettftext($image, $fontSize, 0, (int)$x, (int)$startY, $color, $font, $line);
                $startY += $fontSize + $lineSpacing;
            }
        }


        public function generateImage() {
            $company_id = $_GET['company_id'];
            $process_id = $_GET['process_id'];
            $type = $_GET['type'];
            $user_id = isset($_GET['userId']) ? $_GET['userId'] : null;

            $sql = "SELECT PL.*, C.*, C.district as bairro, PL.district as bairro1, PL.id as process_id, profile_data FROM process_list AS PL
                    LEFT JOIN companies AS C ON C.id = PL.company
                    WHERE PL.id = :id AND PL.company = :company";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                'company' => $company_id,
                'id' => $process_id
            ]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if($type == 'Story'){    
            // Definindo as dimensões da imagem
                $width = 1080;
                $height = 1920;
            }else{
                $width = 1080;
                $height = 1350;
            }
        
            // Criando uma imagem vazia
            $image = imagecreatetruecolor($width, $height);
        
            // Definindo as cores
            $backgroundColor = imagecolorallocate($image, 30, 30, 30);
            $textColor = imagecolorallocate($image, 255, 255, 255);
            $highlightColor = imagecolorallocate($image, 255, 215, 0); // Amarelo
            $titleColor = imagecolorallocate($image, 255, 163, 63);
            
            // Preenchendo o fundo da imagem
            imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor);
        
            // Carregar uma imagem de fundo
            if($type == 'Story'){
                $urlImage = __DIR__ . "/../assets/images/creative_story.png";
            }else{
                $urlImage = __DIR__ . "/../assets/images/creative_feed.png";
            }
            
            $backgroundImage = @imagecreatefrompng($urlImage);
            if (!$backgroundImage) {
                die('Erro ao carregar a imagem de fundo.');
            }
            imagecopyresampled($image, $backgroundImage, 0, 0, 0, 0, $width, $height, imagesx($backgroundImage), imagesy($backgroundImage));
        
            // Carregando fonte (certifique-se de ter esse arquivo no servidor)
            $font = __DIR__ . '/../assets/font/Cabin-Regular.ttf';
            $fontb = __DIR__ . '/../assets/font/Cabin-Bold.ttf';
            if (!file_exists($font)) {
                die('A fonte não foi encontrada.');
            }
            
            if ($result === false) {
                if($type == 'Story'){
                    $this->centerText($image, 'Empresa ou Processo Seletivo não encontrado!!!', $fontb, 32, 1100, $titleColor, $width);    
                }else{
                    $this->centerText($image, 'Empresa ou Processo Seletivos não encontrado!!!', $fontb, 28, 800, $titleColor, $width);    
                }
            }else{
                
                $address = "";
                
                if(!empty($result['state'])){
                    if($result['state'] == 'undefined'){
                        $address = "";
                    }else{
                        $address =  "{$result['bairro1']} - {$result['city']} / {$result['state']}";
                    }
                }else{
                    if($result['companystate'] == 'undefined'){
                        $address = "";
                    }else{
                        $address =  "{$result['bairro']} - {$result['companycity']} / {$result['companystate']}";
                    }
                }
                
                //$address = str_replace(', undefined', '', $address);
                
                if($type == 'Story'){
                    
                    // Adicionando texto à imagem
                    $this->centerMultilineText($image, trim($result['sinonimo']), $fontb, 42, 900, $titleColor, $width);
                    //$this->centerText($image, trim($result['sinonimo']), $fontb, 42, 900, $titleColor, $width);
                    
                    if(!empty($address)){  
                        $this->centerText($image, 'Localização', $font, 28, 980, $titleColor, $width);
                        $this->centerText($image, $address, $font, 28, 1020, $textColor, $width); 
                    }
                    
                    $this->centerText($image, 'Informações', $font, 28, 1080, $titleColor, $width);
                    $this->centerText($image, $this->formatSalary($result['salary']), $font, 28, 1120, $textColor, $width); 
                    $this->centerText($image, trim($result['workregime']) . ' | ' . trim($result['modalityjob']), $font, 28, 1160, $textColor, $width);
                
                    $this->centerText($image, 'Descrição', $font, 28, 1230, $titleColor, $width);
                    $daysList = array_map('trim', explode(',', strtolower($result['daysWeek'])));                    
        
                    $firstDay = $daysList[0];
                    $lastDay = $daysList[count($daysList) - 1];
                    
                    $firstDayLabel = Creative::WEEKDAYS[$firstDay] ?? '';
                    $lastDayLabel  = Creative::WEEKDAYS[$lastDay] ?? '';
                    
                    // Pegando apenas as horas, ignorando os minutos
                    list($hourStart, $minuteStart) = explode(':', $result['start_monday']);
                    list($hourEnd, $minuteEnd) = explode(':', $result['end_monday']);
                    
                    $start_hour = $hourStart . ':' . $minuteStart;
                    $end_hour   = $hourEnd . ':' . $minuteEnd;
                    
                    $textoPeriodo = "Horário das {$start_hour} às {$end_hour}";
                    
                    $this->centerText($image, $textoPeriodo, $font, 28, 1270, $textColor, $width);

                    $description = trim($result['creative_key'] ?? '');
                    
                    if(empty($description)){
                        $requirements = $result['requirements'];
                        
                        $url = 'https://app2.memprega.com.br/api/index.php?action=ai-generator:creative';
    
                        $data = ['requirements' => $requirements, 'process_id' => $result['process_id'], 'sinonimo' => $result['sinonimo'] ];
                        
                        $options = [
                            CURLOPT_URL => $url,
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_POST => true,
                            CURLOPT_POSTFIELDS => http_build_query($data),
                        ];
                        
                        $ch = curl_init();
                        curl_setopt_array($ch, $options);
                        
                        $response = curl_exec($ch);
                        curl_close($ch);
                        $response = json_decode($response, true);
                        $description = $response['text'];
                    }
                    
                    $partes = $this->dividirDescricao($description);
                    
                    // Se veio só uma parte, escreve só ela
                    if (count($partes) == 1) {
                        $this->centerText($image, $partes[0], $font, 28, 1310, $textColor, $width);
                    } else {
                        // Primeira linha
                        $this->centerText($image, $partes[0], $font, 28, 1310, $textColor, $width);
                        // Segunda linha
                        $this->centerText($image, $partes[1], $font, 28, 1340, $textColor, $width);
                    }

                    $profile_data = $result['profile_data'] ?? null;

                    if($profile_data){

                        $profile_data = json_decode($profile_data, true);
                        $gender = $profile_data['gender'] ?? null;
                        $age_min = $profile_data['ageStart'] ?? null;
                        $age_max = $profile_data['ageEnd'] ?? null;

                        if($gender || ($age_min && $age_max))
                            $this->centerText($image, 'Perfil Desejado', $font, 28, 1400, $titleColor, $width);

                        if($gender){
                            $this->centerText($image, "Sexo: " . $gender, $font, 28, 1440, $textColor, $width);
                        }

                        if($age_min && $age_max){
                            $this->centerText($image, "Idade: " . $age_min . " a " . $age_max . " anos", $font, 28, 1480, $textColor, $width); 
                        }                        

                    }                    
                    
                }else{
                    
                    // Adicionando texto à imagem
                    //$this->centerText($image, trim($result['sinonimo']), $fontb, 30, 650, $titleColor, $width);
                    $this->centerMultilineText($image, trim($result['sinonimo']), $fontb, 30, 650, $titleColor, $width);
                    
                    if(!empty($address)){
                        $this->centerText($image, 'Localização', $font, 18, 680, $titleColor, $width);
                        $this->centerText($image, $address, $font, 15, 700, $textColor, $width); 
                    }
                    
                    $this->centerText($image, 'Informações', $font, 18, 750, $titleColor, $width);
                    $this->centerText($image, $this->formatSalary($result['salary']), $font, 15, 780, $textColor, $width); 
                    $this->centerText($image, trim($result['workregime']) . ' | ' . trim($result['modalityjob']), $font, 15, 810, $textColor, $width);
                
                    $this->centerText($image, 'Descrição', $font, 18, 860, $titleColor, $width);
                    $daysList = array_map('trim', explode(',', strtolower($result['daysWeek'])));
        
                    $firstDay = $daysList[0];
                    $lastDay = $daysList[count($daysList) - 1];
                    
                    $firstDayLabel = Creative::WEEKDAYS[$firstDay] ?? '';
                    $lastDayLabel  = Creative::WEEKDAYS[$lastDay] ?? '';
                    
                    // Pegando apenas as horas, ignorando os minutos
                    list($hourStart, $minuteStart) = explode(':', $result['start_monday']);
                    list($hourEnd, $minuteEnd) = explode(':', $result['end_monday']);
                    
                    $start_hour = $hourStart . ':' . $minuteStart;
                    $end_hour   = $hourEnd . ':' . $minuteEnd;
                    //$textoPeriodo = "De {$firstDayLabel} a {$lastDayLabel}, das {$start_hour} às {$end_hour}";
                    $textoPeriodo = "Horário das {$start_hour} às {$end_hour}";
                    
                    $this->centerText($image, $textoPeriodo, $font, 15, 890, $textColor, $width);
                    $description = trim($result['creative_key']);
                    
                    if(empty($description)){
                        $requirements = $result['requirements'];
                        
                        $url = 'https://app2.memprega.com.br/api/index.php?action=ai-generator:creative';
    
                        $data = ['requirements' => $requirements, 'process_id' => $result['process_id'], 'sinonimo' => $result['sinonimo'] ];
                        
                        $options = [
                            CURLOPT_URL => $url,
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_POST => true,
                            CURLOPT_POSTFIELDS => http_build_query($data),
                        ];
                        
                        $ch = curl_init();
                        curl_setopt_array($ch, $options);
                        
                        $response = curl_exec($ch);
                        curl_close($ch);
                        $response = json_decode($response, true);
                        $description = $response['text'];
                    }
                    
                    $partes = $this->dividirDescricao($description);
                    
                    // Se veio só uma parte, escreve só ela
                    if (count($partes) == 1) {
                        $this->centerText($image, $partes[0], $font, 15, 910, $textColor, $width);
                    } else {
                        // Primeira linha
                        $this->centerText($image, $partes[0], $font, 15, 910, $textColor, $width);
                        // Segunda linha
                        $this->centerText($image, $partes[1], $font, 15, 940, $textColor, $width);
                    }

                    $profile_data = $result['profile_data'] ?? null;

                    if($profile_data){

                        $profile_data = json_decode($profile_data, true);
                        $gender = $profile_data['gender'] ?? null;
                        $age_min = $profile_data['ageStart'] ?? null;
                        $age_max = $profile_data['ageEnd'] ?? null;

                        if($gender || ($age_min && $age_max))
                            $this->centerText($image, 'Perfil Desejado', $font, 18, 990, $titleColor, $width);

                        if($gender){
                            $this->centerText($image, "Sexo: " . $gender, $font, 15, 1020, $textColor, $width);
                        }

                        if($age_min && $age_max){
                            $this->centerText($image, "Idade: " . $age_min . " a " . $age_max . " anos", $font, 15, 1040, $textColor, $width); 
                        }                        

                    }


                }
            }
            
            // Exibindo a imagem gerada
            header('Content-Type: image/png');
            imagepng($image);
            imagedestroy($image);

            if($user_id) {
                include_once __dir__ .  '/../core/LogEvent.php';
                $title = "Gerou criativo do tipo \"$type\"";
                $url = "/recruiter/process";
                $log_type = null;

                switch($type) {
                    case 'Story':   $log_type = LogEvent::CREATIVE_SHARE_STORY  ; break;
                    case 'Feed':    $log_type = LogEvent::CREATIVE_SHARE_FEED   ; break;
                }
                
                LogEvent::log($user_id, $process_id, $url, $title, $log_type);

            }
        }

    }