<?php

    class Profile extends Core {
        
        function updateShowInfo() {

            $id = $_POST['id'];
            $show = $_POST['showInfo'] ?? false;
            $show = $show == 'true' ? true : false;
            $sql = "UPDATE professional_experiences SET mostrar_experiencias = :show_info  WHERE lead_id = :id";

            $stmt = parent::$conn->prepare($sql);
            $stmt->bindParam(':show_info', $show);
            $stmt->bindParam(':id', $id);
            $stmt->execute();

            $sql = "UPDATE education_experience  SET mostrar_experiencias = :show_info  WHERE lead_id = :id";

            $stmt = parent::$conn->prepare($sql);
            $stmt->bindParam(':show_info', $show);
            $stmt->bindParam(':id', $id);
            $stmt->execute();

            $sql = "UPDATE leads SET mostrar_experiencias = :show_info  WHERE id = :id";

            $stmt = parent::$conn->prepare($sql);
            $stmt->bindParam(':show_info', $show);
            $stmt->bindParam(':id', $id);
            $stmt->execute();

            return [ 'type' => 'OK' ];

        }

        function store() {

            $firstname = $_POST['firstname'];
            $lastname = $_POST['lastname'];
            $email = $_POST['email'];
            $cpf = $_POST['cpf'];
            $phone = $_POST['phone'];
            $mobile = $_POST['mobile'];	
            $gender = $_POST['gender'];
            $birthday = $_POST['birthday'];
            $zipcode = $_POST['zipCode'];
            $state = $_POST['state'];
            $city = $_POST['city'];
            $district = $_POST['district'];
            $street = $_POST['street'];
            $number = $_POST['number'];
            $complement = $_POST['complement'];

            $sql = "UPDATE leads SET firstname = :firstname, 
                lastname = :lastname, 
                email = :email, cpf = :cpf, 
                phone = :phone, 
                mobile = :mobile,	
                gender = :gender, 
                birthdate = :birthdate, 
                zipcode = :zipcode, 
                state = :state, 
                city = :city, 
                district = :district, 
                address1 = :street, 
                address2 = :number, 
                complement = :complement
                WHERE email = :email
            ";

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute(
                array(
                    ':firstname' => $firstname,
                    ':lastname' => $lastname, 
                    ':email' => $email, 
                    ':cpf' => $cpf, 
                    ':phone' => $phone,
                    ':mobile' => $mobile,
                    ':gender' => $gender, 
                    ':birthdate' => $birthday, 
                    ':zipcode' => $zipcode, 
                    ':state' => $state,
                    ':city' => $city,
                    ':district' => $district, 
                    ':street' => $street, 
                    ':number' => $number,
                    ':complement' => $complement
                )            
            );

            return [ 'type' => 'OK', 'data' => $stmt->rowCount() ];

        }

        function get() {

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

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

        }
        
        function getinfo() {

            $id =  $_GET['id'];
            $sql = "SELECT leads.email, leads.id, leads.firstname, leads.lastname, A2.company_id, leads.phone, DATE_FORMAT(leads.birthdate, '%d/%m/%Y') AS birthdate, leads.cpf, A3.companyname, A3.cnpj, A3.companyaddress1, A3.companyaddress2, A3.companycity, A3.companystate, A3.companyzipcode, A3.district, A3.complement FROM leads 
            LEFT JOIN companies_leads as A2 ON A2.lead_id = leads.id 
            LEFT JOIN companies AS A3 ON A3.id = A2.company_id
            WHERE leads.id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            if($result){
                return [ 'type' => 'OK', 'data' => $result ];
            }else{
                return [ 'type' => 'FAIL', 'data' => $result ];
            }

        }

        function getAvatarProfile() {

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

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

        }


        // function upload() {

        //     $id =  $_POST['id'];
        //     $uploaddir = __dir__ . '/../uploads/avatars/';
        //     $filename = basename($_FILES['avatar']['name']);
        //     $uploadfile = $uploaddir . $filename;
        //     //$real_filename = uniqid('avatar_') . '.png';
        //     $real_filename = "avatar_{$id}.png";
        //     $dir_file = $uploaddir . $real_filename;

        //     if (!move_uploaded_file($_FILES['avatar']['tmp_name'], $uploadfile))
        //         return ['type' => 'FAIL', 'data' => 'Não foi possivel processar upload'];

        //     list($width, $height) = getimagesize($uploadfile);
            
        //     if($width > 1000) {
        //         $image_type = $_FILES['avatar']['type'];
        //         $image = ($image_type === 'image/jpeg')
        //             ? imagecreatefromjpeg($uploadfile)
        //             : imagecreatefrompng($uploadfile);
                
        //         $image = imagescale($image, 1000);
        //         if($image_type === 'image/jpeg')
        //             imagejpeg($image, $dir_file);
        //         else imagepng($image, $dir_file);
                
        //     } else
        //         copy($uploadfile, $dir_file);
            
        //     @unlink($uploadfile);

        //     $public_link = '/uploads/avatars/' . $real_filename;
            
        //     $sql = "UPDATE leads SET avatar_profile = '$public_link' WHERE id = ?";
        //     $stmt = parent::$conn->prepare($sql);
        //     $stmt->execute([ $id ]);

        //     return [ 'type' => 'OK' ];

        // }

        
        function upload() {
            
            if (isset($_POST['id'])) {
                $id = $_POST['id'];
            } elseif (isset($_GET['id'])) {
                $id = $_GET['id'];
            } else {
                return ['type' => 'FAIL', 'data' => 'Parâmetro ID não fornecido'];
            }
            
            $uploaddir = __DIR__ . '/../uploads/avatars/';
            $filename = "avatar_{$id}.png";
            $uploadfile = $uploaddir . $filename;
        
            // Verificar se o campo 'avatar_bytes' está presente
            if (isset($_POST['avatar_bytes'])) {
                // Decodificar os bytes base64
                $imageBytes = base64_decode($_POST['avatar_bytes']);
                // Obter o tipo de MIME dos bytes
                $image_type = 'image/png';
            } else {
                // Verificar se o arquivo foi enviado corretamente
                if (!isset($_FILES['avatar']) || empty($_FILES['avatar']['tmp_name'])) {
                    return ['type' => 'FAIL', 'data' => 'Arquivo de imagem não enviado'];
                }
        
                // Obter o tipo de MIME a partir de $_FILES
                $image_type = $_FILES['avatar']['type'];
                // Ler os bytes do arquivo
                $imageBytes = file_get_contents($_FILES['avatar']['tmp_name']);
            }
        
            // Verificar se o tipo de imagem é suportado
            if (strpos($image_type, 'image/') !== false) {
                // Verificar se o diretório de upload existe
                if (!file_exists($uploaddir)) {
                    mkdir($uploaddir, 0777, true);
                }
        
                // Salvar a imagem no diretório de upload
                if (file_put_contents($uploadfile, $imageBytes) === false) {
                    return ['type' => 'FAIL', 'data' => 'Não foi possível processar o upload'];
                }
        
                // Realizar outras operações, como redimensionar a imagem, se necessário
        
                $public_link = '/uploads/avatars/' . $filename;
        
                $sql = "UPDATE leads SET avatar_profile = ? WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$public_link, $id]);
        
                return ['type' => 'OK'];
            } else {
                return ['type' => 'FAIL', 'data' => 'Tipo de arquivo não suportado'];
            }
        }


        
        function getSignatureStatus() {

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

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

        }
        
        function makePaid() {

            $email =  $_POST['email'];
            $sql = "UPDATE leads SET signature_status = 'ACTIVE', voucher = NULL, signature_date = NOW(), signature_status_text = 'Conta gratis Candidato' WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $email ]);

            return [ 'type' => 'OK' ];

        }

        function appInstall() {

            $id = $_POST['userId'];

            $sql = "DELETE FROM lead_lists_leads WHERE leadlist_id IN (40, 43) AND lead_id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);
            
            $sql = "INSERT INTO lead_lists_leads(leadlist_id, lead_id, date_added, manually_removed, manually_added)
                    VALUES(40, ?,NOW(), 0, 0)";   
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);

            return [ 'type' => 'OK' ];

        }

        function removeInfo(){
            
            $id = $_POST['id'];

            $sql = "DELETE FROM leads WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);
            
            $sql = "DELETE FROM lead_lists_leads WHERE lead_id = ?";   
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);

            return [ 'type' => 'OK' ];
        }

    }