<?php
include_once __dir__ . '/../vendor/autoload.php';
include_once __dir__ .  '/../core/LogEvent.php';

use Smalot\PdfParser\Parser;
use Dompdf\Dompdf;

class Curriculo extends Core
{

    function upload()
    {

        try {

            if (isset($_FILES['curriculo']) && $_FILES['curriculo']['error'] === UPLOAD_ERR_OK) {

                $parser = new Parser();
                $pdf = $parser->parseFile($_FILES['curriculo']['tmp_name']);

                unlink($_FILES['curriculo']['tmp_name']);
                $text = '';
                foreach ($pdf->getPages() as $page) {
                    $text .= $page->getText();
                }

                if(!preg_match('//u', $text)) {
                    $text = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $text);
                }
                
                $user_id = $_POST['userId'];
                $sql = "INSERT INTO leads_curriculo(lead_id, content) VALUES(?, ?) ON DUPLICATE KEY UPDATE content = ?, date_created = NOW()";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    $user_id,
                    $text,
                    $text
                ]);

                return ['type' => 'OK', 'data' => $text];
            } else {
                return ['type' => 'ERROR', 'message' => $_FILES['curriculo']['error']];
            }
        } catch (\Exception $err) {
            return ['type' => 'ERROR', 'message' => $err->getMessage()];
        }
    }

    function updateContent()
    {

        try {

            $data = $_POST;
            $sql = "UPDATE leads_curriculo SET content = ? WHERE lead_id = ?";

            $content = strip_tags($data['content']);
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                $content,
                $data['userId']
            ]);

            return ['type' => 'OK'];
        } catch (\Exception $err) {
            return ['type' => 'OK', 'error' => $err->getMessage()];
        }
    }

    function get()
    {

        try {

            $id = $_GET['id'];
            $sql = "SELECT * FROM leads_curriculo WHERE lead_id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            return ['type' => 'OK', 'data' => $result];
        } catch (\Exception $err) {
            return ['type' => 'ERROR', 'message' => $err->getMessage()];
        }
    }

    function verifyDownload()
    {

        $user_id = $_GET['userId'];
        $sql = "SELECT firstname, lastname, sobre_candidato, desired_job_title, avatar_profile, first_job, aboutme FROM leads WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$user_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        // HTML que você deseja converter para PDF
        $html = file_get_contents(__dir__ . '/../core/pdf/templates/curriculo.html');
        $html = str_replace("#{avatar}", __DIR__ . "/../{$result['avatar_profile']}", $html);
        $html = str_replace("#{fullname}", "{$result['firstname']} {$result['lastname']}", $html);
        $html = str_replace("#{desired_job_title}", $result['desired_job_title'] ?? '', $html);
        $html = str_replace("#{about_me}", $result['aboutme'] ?? '', $html);

        $sql = "SELECT * FROM professional_experiences WHERE lead_id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$user_id]);
        $professional_experiences = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM education_experience WHERE lead_id = ?";
        $stmt_2 = parent::$conn->prepare($sql);
        $stmt_2->execute([$user_id]);
        $education_experiences = $stmt_2->fetchAll(PDO::FETCH_ASSOC);

        $empty = [];

        if (empty(trim($result['aboutme'] ?? '')))
            $empty['sobre_candidato'] = true;

        if (sizeof($professional_experiences) == 0 && $result['first_job'] <> 'true')
            $empty['professional_experiences'] = true;

        if (sizeof($education_experiences) == 0)
            $empty['education_experiences'] = true;

        return [
            'type' => 'OK',
            'data' => [
                'empty' => $empty,
                'first_job' => $result['first_job']
            ]
        ];
    }

    function download()
    {

        $user_id = $_GET['userId'];
        $lead_id = $_GET['candidateId'];
        $share = $_GET['share'] ?? 0;
        $sql = "SELECT * FROM leads WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$lead_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $html = file_get_contents(__dir__ . '/../core/pdf/templates/curriculo.html');
        
        if(!empty($result['avatar_profile'])) {
            $html = str_replace("#{avatar}", "https://app2.memprega.com.br/api/" . "{$result['avatar_profile']}", $html);
        }else{
             $html = str_replace("#{styles_photo}", "style='display:none;'", $html);
        }
        
        $html = str_replace("#{fullname}", "{$result['firstname']} {$result['lastname']}", $html);
        $html = str_replace("#{about_me}", $result['aboutme'], $html);

        $cityParts = explode(',', $result['city']);

        $full_address =  $result['address1'] . ' ' . $result['address2'] . ', <br>' . trim($cityParts[0]) . ' - ' . $result['state'] . ', ' . $this->formatCep($result['zipcode']);
        $html = str_replace("#{email}", $result['email'], $html);
        $html = str_replace("#{phone}", $this->formatPhone($result['phone']), $html);
        $html = str_replace("#{address}", $full_address, $html);

        $desired_job_titles = explode(',', $result['desired_job_title']);
        $desired_jobs = '<ul>';

        foreach ($desired_job_titles as $job)
            $desired_jobs .= "<li>" . trim($job) . "</li>";

        $desired_jobs .= '</ul>';
        $html = str_replace("#{desired_jobs}", $desired_jobs, $html);

        $sql = "SELECT * FROM professional_experiences WHERE lead_id = ? ORDER BY init_date DESC";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$lead_id]);
        $professional_experiences = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM education_experience WHERE lead_id = ? AND education_level != 'curso-extra' ORDER BY date_start DESC";
        $stmt_2 = parent::$conn->prepare($sql);
        $stmt_2->execute([$lead_id]);
        $education_experiences = $stmt_2->fetchAll(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM education_experience WHERE lead_id = ? AND education_level = 'curso-extra' ORDER BY date_start DESC";
        $stmt_3 = parent::$conn->prepare($sql);
        $stmt_3->execute([$lead_id]);
        $courses = $stmt_3->fetchAll(PDO::FETCH_ASSOC);
        
        //experiencias profissionais
        if (sizeof($professional_experiences) == 0) {
            $html = str_replace("#{styles}", 'style="display: none"', $html);
        } else {

            $html = str_replace("#{styles}", '', $html);
            $professional_experiences_list = "";

            foreach ($professional_experiences as $item) {

                $date_start = date('d/m/Y', strtotime($item['init_date']));
                $date_end = !empty($item['final_date']) ? date('d/m/Y', strtotime($item['final_date'])) : 'até o momento';
                $job_description = strip_tags(trim($item['description']));
                $job_title = $item['sinonimo'] ?? 'Não informado';
                $content = "
                        <div class='row'>
                            <div class='title-wrapper'>
                                <p>$date_start - $date_end</p>
                            </div>
                            <div class='content-wrapper'>
                                <p class='title'>$job_title, em {$item['organization']}</p>                                
                                <ul>
                                    <li style=\"page-break-inside: avoid;\">
                                        {$job_description}
                                    </li>
                                </ul>
                            </div>
                        </div>
                    ";

                $professional_experiences_list .= $content;
            }
        }

        $html = str_replace("#{profissional_experience}", $professional_experiences_list, $html);

        $education_level = [
            'curso-extra' => 'Curso/especialização',
            'curso-tecnico' => 'Curso técnico',
            'ens-fun-nivel' => 'Ensino fundamental',
            'ens-med-nivel' => 'Ensino médio',
            'ens-sup-nivel' => 'Graduação',
            'ens-sup-nivel2' => 'Pós graduação',
            'ens-sup-nivel3' => 'Mestrado',
            'ens-sup-nivel4' => 'Doutorado'
        ];

        //Experiencia educacionais
        $education_experiences_list = "";

        foreach ($education_experiences as $item) {

            $date_start = date('d/m/Y', strtotime($item['date_start']));
            $date_end = !empty($item['date_end']) ? date('d/m/Y', strtotime($item['date_end'])) : 'o momento';
            $ed_level = isset($item['education_level']) && !empty($item['education_level']) 
                ? $education_level[$item['education_level']] 
                : (
                    isset($result['leveleducation']) && !empty($result['leveleducation'])
                        ? $education_level[$result['leveleducation']]
                        : ''
                );
            $course_name = $item['course_name'] ? '- ' . $item['course_name'] : '';
            $content = "
                    <div class='row'>
                        <div class='title-wrapper'>
                            <p>$ed_level $course_name</p>
                        </div>
                        <div class='content-wrapper'>
                            <p style=\"page-break-inside: avoid;\">{$item['institution_name']}, de $date_start até $date_end</p>
                        </div>
                    </div>
                ";

            $education_experiences_list .= $content;
        }

        $html = str_replace("#{education_experience}", $education_experiences_list, $html);
        //Verificação do cursos para mostrar no Curriculo
        if (empty($courses)) {
            $html = str_replace("#{styles_courses}", 'style="display: none"', $html);
        } else if (sizeof($courses)) {

            //Cursos extras
            $courses_list = "";

            foreach ($courses as $item) {

                $date_start = date('d/m/Y', strtotime($item['date_start']));
                $date_end = !empty($item['date_end']) ? date('d/m/Y', strtotime($item['date_end'])) : 'até o momento';
                $ed_level = isset($item['education_level']) ? $education_level[$item['education_level']] : '';
                $content = "
                        <div class='row'>
                            <div class='title-wrapper'>
                                <p>$ed_level - {$item['course_name']}</p>
                            </div>
                            <div class='content-wrapper'>
                                <p>{$item['institution_name']}, de $date_start até $date_end</p>
                            </div>
                        </div>
                    ";

                $courses_list .= $content;
            }

            $html = str_replace("#{courses}", $courses_list, $html);
        }

        $dompdf = new Dompdf(array('enable_remote' => true));
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream("{$result['firstname']}_{$result['lastname']}_Curriculo.pdf", array("Attachment" => 1));
        $share = intval($share);    
        
        if($share == 1) {
            $title = "Baixou o curriculo de \"{$result['firstname']} {$result['lastname']}\"";
            $url = "";            
            LogEvent::log($user_id, $lead_id, $url, $title, LogEvent::SHARED_CURRICULO);
        } else {
            $title = "Baixou o seu curriculo";
            $url = "";
            LogEvent::log($user_id, $user_id, $url, $title, LogEvent::DOWNLOAD_CURRICULO, true);
        }

    }

    // Função para formatar o Telefone
    function formatPhone($phone)
    {
        // Remover todos os caracteres não numéricos
        $phone = preg_replace('/[^0-9]/', '', $phone);

        // Verificar se o número tem 10 ou 11 dígitos
        if (strlen($phone) == 10) {
            // Formatar número de 10 dígitos (XX) XXXX-XXXX
            $formattedPhone = preg_replace('/(\d{2})(\d{4})(\d{4})/', '($1) $2-$3', $phone);
        } elseif (strlen($phone) == 11) {
            // Formatar número de 11 dígitos (XX) XXXXX-XXXX
            $formattedPhone = preg_replace('/(\d{2})(\d{5})(\d{4})/', '($1) $2-$3', $phone);
        } else {
            // Retornar o número original se não tiver 10 ou 11 dígitos
            $formattedPhone = $phone;
        }

        return $formattedPhone;
    }

    // Função para formatar o CEP
    function formatCep($cep)
    {
        // Remover todos os caracteres não numéricos
        $cep = preg_replace('/[^0-9]/', '', $cep);

        // Verificar se o CEP tem 8 dígitos
        if (strlen($cep) == 8) {
            // Formatar CEP de 8 dígitos XXXXX-XXX
            $formattedCep = preg_replace('/(\d{5})(\d{3})/', '$1-$2', $cep);
        } else {
            // Retornar o CEP original se não tiver 8 dígitos
            $formattedCep = $cep;
        }

        return $formattedCep;
    }
}
