<?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 = isset($_POST['mobile']) ? $_POST['mobile'] : null;
        $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 = isset($_POST['complement']) ? $_POST['complement'] : null;
        $sobre = $_POST['aboutme'];
        $is_pcd = $_POST['isPcd'];
        $pcd_description = $_POST['pcdDescription'];

        $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,
                aboutme = :sobre,
                is_pcd = :is_pcd,
                skype = :pcd_description,
                identificacao_do_genero = :pcd_description
                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,
                ':sobre' => $sobre,
                ':is_pcd' => $is_pcd,
                ':pcd_description' => $pcd_description
            )
        );

        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.companyphone, 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()
    {

        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 makeTrial()
    {

        // Checa se e-mail e método de pagamento foram fornecidos
        if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            return ['type' => 'FAIL', 'message' => 'Dados inválidos'];
        }

        $email = $_POST['email'];

        // Preparar e executar a consulta SQL
        $sql = "UPDATE companies SET signature_status = 'TRIAL', signature_status_text = 'periodo de teste' WHERE companyemail = :email";
        try {
            $stmt = parent::$conn->prepare($sql);
            if ($stmt->execute([':email' => $email])) {
                return ['type' => 'OK'];
            }
            return ['type' => 'FAIL', 'message' => 'Falha ao atualizar o registro'];
        } catch (PDOException $e) {
            return ['type' => 'FAIL', 'message' => 'Erro no banco de dados: ' . $e->getMessage()];
        }
    }

    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 = "UPDATE leads SET firstname = '', lastname = '', email = '',  phone = '', mobile = '', address1 = '', address2 = '', cpf = '', rg = '', password = '', complement = ''  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'];
    }

    function updateTermos()
    {

        $email =  $_POST['email'];
        $planCode =  $_POST['planCode'];
        $planSignature =  $_POST['planSignature'];
        $acceptContract =  $_POST['acceptContract'];
        $acceptTerm =  $_POST['acceptTerm'];

        $sql = "UPDATE leads SET plan_signature = ?, accept_term = ?, acceptcontract = ?, signature_plan_id = ?  WHERE email = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$planSignature, $acceptTerm, $acceptContract, $planCode, $email]);

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

    function saveSignaturePlan() {
        
        $logFile = 'signatureUpdade.log';
        try {
            parent::$conn->beginTransaction(); // ✅ Inicia a transação
            $plan_id = $_POST['plan_id'] ?? null;
            if($plan_id == 1){
                $plan_payment_id = 13;
                $plan_payment_option_id = null;
                $status = 'ACTIVE';
            }else{    
                $plan_payment_id = $_POST['plan_payment_id'] ?? null;
                $plan_payment_option_id = $_POST['plan_payment_option_id'] ?? null;
            }
            $company_id = $_POST['companyId'] ?? null;
            // Se tiver CNPJ preenchido, faz as atualizações da empresa
            if (!empty($_POST['cnpj'])) {
                $companyname = trim($_POST['companyname']);
                $cnpj = preg_replace('/\D/', '', $_POST['cnpj']);
                $companyemail = trim($_POST['companyemail']);
                $companyphone = preg_replace('/\D/', '', $_POST['companyphone']);
                $companyzipcode = preg_replace('/\D/', '', $_POST['companyzipcode']);
                $companystate = trim($_POST['companystate']);
                $companycity = trim($_POST['companycity']);
                $district = trim($_POST['district']);
                $companyaddress1 = trim($_POST['companyaddress1']);
                $companyaddress2 = trim($_POST['companyaddress2']);
                $complement = !empty($_POST['complement']) ? trim($_POST['complement']) : null;
                $fullname = trim($_POST['fullname']);
                // 👇 Trata o campo companystate (pode vir como JSON)
                if ($companystate) {
                    if (is_string($companystate) && strpos(trim($companystate), '{') === 0) {
                        $decoded = json_decode($companystate, true);
                        if (json_last_error() === JSON_ERROR_NONE && isset($decoded['sigla'])) {
                            $companystate = strtoupper(trim($decoded['sigla']));
                        }
                    }
                }
                // Divide o nome em primeiro e sobrenome
                $parts = explode(' ', $fullname);
                $firstname = array_shift($parts);
                $lastname = implode(' ', $parts);
                // Normaliza cidade para formato "Cidade, UF"
                if ($companystate && !str_contains($companycity, ',')) {
                    $companycity = "{$companycity}, {$companystate}";
                }
                // Validação mínima
                if (!$companyname || !$companyemail || !$cnpj) {
                    throw new Exception('Campos obrigatórios ausentes.');
                }
                // Atualiza tabela leads
                $sql = "UPDATE leads SET firstname = ?, lastname = ?, email = ? WHERE email = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$firstname, $lastname, $companyemail, $companyemail]);
                // Atualiza tabela companies
                $sql = "UPDATE companies 
                        SET companyname = ?, cnpj = ?, companyemail = ?, companyphone = ?, companyzipcode = ?, 
                            companystate = ?, companycity = ?, district = ?, 
                            companyaddress1 = ?, companyaddress2 = ?, complement = ? 
                        WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([
                    $companyname, $cnpj, $companyemail, $companyphone, $companyzipcode,
                    $companystate, $companycity, $district,
                    $companyaddress1, $companyaddress2, $complement, $company_id
                ]);
            }
            // Busca assinatura da empresa
            $sql = "SELECT id FROM `company_signatures` WHERE company_id = :company_id AND type = 'signature'";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([':company_id' => $company_id]);
            $company_signature = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$company_signature) {
                throw new Exception("Assinatura não encontrada para a empresa ID {$company_id}.");
            }
            $signature_id = $company_signature['id'];
            if($plan_id == 1){
                $price = '0.00';
            }else{
                //Busca o preço do plano
                $sql2 = "SELECT price FROM `plan_payment_options` WHERE plan_payment_id = :plan_payment_id AND id = :plan_payment_option_id";
                $stmt2 = parent::$conn->prepare($sql2);
                $stmt2->execute([':plan_payment_id' => $plan_payment_id, ':plan_payment_option_id' => $plan_payment_option_id ]);
                $plan_payment = $stmt2->fetch(PDO::FETCH_ASSOC);
                if (!$plan_payment) {
                    throw new Exception("Preço não encontrada para a empresa ID {$company_id}.");
                }
                $price = $plan_payment['price'];
            } 
            // Atualiza assinatura do plano
            if(!empty($status)){
                $sql = "UPDATE company_signatures 
                    SET plan_id = ?, plan_payment_id = ?, plan_payment_option_id = ?, price = ?, status = 'ACTIVE' 
                    WHERE company_id = ? AND type = 'signature'";
            }else{
                $sql = "UPDATE company_signatures 
                    SET plan_id = ?, plan_payment_id = ?, plan_payment_option_id = ?, price = ? 
                    WHERE company_id = ? AND type = 'signature'";
            }
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$plan_id, $plan_payment_id, $plan_payment_option_id, $price, $company_id]);
            // Busca período do contrato
            $sql = "SELECT period FROM `plan_payment_contracts` WHERE id = :id_payment AND plan_id = :plan_id;";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([':id_payment' => $plan_payment_id, ':plan_id' => $plan_id]);
            $periods = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$periods) {
                throw new Exception("Contrato de pagamento não encontrado para plan_id {$plan_id}.");
            }
            $period = $periods['period'];
            // Copia regras para a empresa
            $sql = "SELECT * FROM plan_options WHERE plan_id = :plan_id AND quota_period = :period";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([':plan_id' => $plan_id, ':period' => $period]);
            $options = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $sql_delete_quote = "DELETE FROM signature_quotes WHERE company_id = ?";
            $stmt_delete_quote = parent::$conn->prepare($sql_delete_quote);
            $stmt_delete_quote->execute([$company_id]);
            $sql = "INSERT INTO signature_quotes(signature_id, company_id, plan_id, plan_option_id, `value`)
                    VALUES(:signature_id, :company_id, :plan_id, :option_id, :value)";
            foreach ($options as $option) {
                $stmt_option = parent::$conn->prepare($sql);
                $stmt_option->execute([
                    ':signature_id' => $signature_id,
                    ':company_id' => $company_id,
                    ':plan_id' => $plan_id,
                    ':option_id' => $option['id'],
                    ':value' => $option['quota_value']
                ]);
            }
            parent::$conn->commit(); // ✅ Tudo certo, confirma a transação
            return ['type' => 'OK'];
        } catch (Exception $e) {
            parent::$conn->rollBack(); // ❌ Reverte tudo
            // 🔥 Log detalhado com data/hora
            $timestamp = date('Y-m-d H:i:s');
            $message = "[{$timestamp}] [saveSignaturePlan] ERRO empresa ID {$company_id}: " . $e->getMessage() . PHP_EOL;
            file_put_contents($logFile, $message, FILE_APPEND);
            return ['type' => 'ERROR', 'message' => 'Erro ao salvar plano: ' . $e->getMessage()];
        }
    }

    function suspendInfo()
    {

        $id = $_POST['id'];
        $status = $_POST['status'];

        $sql = "UPDATE leads SET signature_status = ? WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$status, $id]);

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

    function getByEmail()
    {
        $email = $_POST['email'];
        $sql = "SELECT id, CONCAT(firstname, ' ', lastname) AS full_name FROM leads WHERE email = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$email]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
 
        return ['type' => 'OK', 'data' => $result];
    }
    
    function makePendingPayment() {

        $email = $_POST['email'];       
        
        $sql = "UPDATE companies SET signature_status = 'PENDING', signature_status_text = 'Erro no processamento do cartão' WHERE email = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$email]);

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

    }
}
