<?php

    class Company extends Core {

        function get() {
            
            $id = $_GET['id'];
            $sql = "SELECT * FROM companies WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            $cnpjws = false;
            if(empty($result['ie']) || empty($result['tax_regime'])) {

                $response = $this->getByCNPJWS($result['cnpj']);
                if($response) {
                    $result['ie'] = $response['ie'];
                    $result['tax_regime'] = $response['tax_regime'];
                    $cnpjws = true;
                }

            }

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

        }

        function update() {

            $id = $_POST['id'];
            $businessname = $_POST['businessName'];
            $companyname = $_POST['companyName'];
            $cnpj = $_POST['cnpj'];
            $ie = $_POST['ie'];
            $im = $_POST['im'];
            $tax_regime = $_POST['taxRegime'];
            $zip_code = $_POST['zipCode'];
            $state = $_POST['state'];
            $city = $_POST['city'];
            $street = $_POST['street'];
            $district = $_POST['district'];
            $number = $_POST['number'];
            $complement = $_POST['complement'];
            $email = $_POST['email'];
            $companyphone = $_POST['companyphone'];
            $site = $_POST['site'];
            $facebook = $_POST['facebook'];
            $instagram = $_POST['instagram'];
            $youtube = $_POST['youtube'];
            $website = $_POST['website'];

            if (empty($ie) || empty($tax_regime)) {
                $response = $this->getByCNPJWS($cnpj);

                if ($response) {
                    $ie = $response['ie'];
                    $tax_regime = $response['tax_regime'];
                }                
            }
            
            $sql = "UPDATE companies 
                SET companyname = :companyname, companyaddress1 = :companyaddress1, companyaddress2 = :companyaddress2,
                    companycity = :companycity, companystate = :companystate, companyzipcode = :companyzipcode,
                    companywebsite = :companywebsite, companyphone = :companyphone,
                    businessname = :businessname, ie = :ie, cnpj = :cnpj, im = :im,
                    tax_regime = :tax_regime, district = :district, complement = :complement, 
                    instagram = :instagram, youtube = :youtube, facebook = :facebook
                WHERE id = :id";

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                ':companyname' => $companyname,
                ':companyaddress1' => $street,
                ':companyaddress2' => $number,
                ':companycity' => $city,
                ':companystate' => $state,
                ':companyzipcode' => $zip_code,
                ':companywebsite' => $site,
                ':companyphone' => $companyphone,
                ':businessname' => $businessname,
                ':ie' => $ie,
                ':cnpj' => $cnpj,
                ':im' => $im,
                ':tax_regime' => $tax_regime,
                ':district' => $district,
                ':complement' => $complement,
                ':instagram' => $instagram,
                ':youtube' => $youtube,
                ':facebook' => $facebook,
                ':id' => $id
            ]);
            
            return [ 'type' => 'OK' ];

        }
        
        function total() {

            $sql = "SELECT count(*) as records FROM companies";
            $stmt = parent::$conn->query($sql);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

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

        }

        function list() {

            $limit = $_GET['limit'] ?? 20;
            $page_index = $_GET['pageIndex'] ?? 0;
            $offset = $page_index * $limit;
            $search = $_GET['search'] ?? null;

            $where = "";
            $bind_params = [
                ':offset' => intval($offset),
                ':limit' => intval($limit)
            ];

            if($search) {
                $where = "WHERE companyemail like :search OR companyname like :search OR CNPJ like :search";
                $bind_params[':search'] = "%$search%";
            }

            $sql = "SELECT * FROM companies $where LIMIT :offset, :limit";
            $stmt = parent::$conn->prepare($sql);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);

            if($search) {
                $searchParam = "%$search%";
                $stmt->bindParam(':search', $searchParam, PDO::PARAM_STR);
            }

            $stmt->execute();
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

        }

        function updateVoucher() {

            $id = $_POST['id'];
            $enable = $_POST['enable'] == 'true';

            $voucher = $enable ? substr(uniqid(), 0, 8) : null;
            $sql = "UPDATE companies SET voucher = ? WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $voucher, $id ]);

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

        }
        
        function updateCupom() {

            $lead = $_POST['user'];
            $cupom = $_POST['code'];
            
            $column = strpos($lead, '@') !== false ? 'companyemail' : 'id';
            $sql = "SELECT cnpj, companyemail, cupom FROM companies WHERE $column = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$lead]);
            
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!empty($row['cupom'])) {
                return ['type' => 'FAIL'];
            }
            
            // $sql = "SELECT cnpj FROM companies WHERE companyemail = ?";
            // $stmt = parent::$conn->prepare($sql);
            // $stmt->execute([$row['email']]);
            
            // $row = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!empty($row['cnpj'])) {
                $cnpj_base64 = base64_encode($row['cnpj']);
                $sql = "SELECT COUNT(*) FROM cupons WHERE cupom = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$cnpj_base64]);
                
                $count = $stmt->fetchColumn(); // Obter o resultado da contagem
            
                if ($count <= 0) {
                  return ['type' => 'FAIL'];
                }
                
            }
            
            $sql = "UPDATE companies SET signature_status = 'TRIAL', cupom = ? WHERE $column = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$cupom, $lead]);
            
            if ($stmt->rowCount() > 0) {
                return ['type' => 'OK']; // Cupom aplicado com sucesso
            } else {
                return ['type' => 'FAIL']; // Update falhou
            }

        }

        function updateShowUserData() {

            $id = $_POST['id'];
            $enable = $_POST['enable'] == 'true';

            $show_user_data = $enable ? 'true' : null;
            $sql = "UPDATE companies SET show_user_data = ? WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            
            $stmt->execute([ $show_user_data, $id ]);

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

        }

        function removeInfo(){
            
            $id = $_POST['id'];
            $id_user = $_POST['id_user'];
            
            $sql = "SELECT lead_id FROM `companies_leads` WHERE company_id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);
            $companyIds = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            if($companyIds){
                $sql_del = "DELETE FROM `companies_leads` WHERE company_id = ? AND lead_id = ?";
                $stmt2 = parent::$conn->prepare($sql_del);
                
                foreach ($companyIds as $company) {
                    $leads_id = $company['lead_id'];
                    $stmt2->execute([ $id, $leads_id ]);
                    
                    $sql3 = "DELETE FROM leads WHERE id = ?";
                    $stmt3 = parent::$conn->prepare($sql);
                    $stmt3->execute([ $leads_id ]);
                    
                }
            }            
            
            $sql = "DELETE FROM lead_lists_leads WHERE lead_id = ?";   
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id_user ]);
            
            $sql = "DELETE FROM companies WHERE id = ?";   
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id ]);
            
            $sql = "DELETE FROM companies_leads WHERE company_id = ? and lead_id = ?";   
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id, $id_user ]);
            
            return [ 'type' => 'OK', 'post' => $_POST ];
        }
        
        function paymentinfo() {
            $lead_id = $_POST['userId'];
            $payment_type = $_POST['payment_type'];
            
            // Decodifica os dados JSON de step1 e step2
            $step1 = json_decode($_POST['step1'], true);
            $step2 = json_decode($_POST['step2'], true);
        
            // Verifica se a decodificação foi bem-sucedida
            if (json_last_error() !== JSON_ERROR_NONE) {
                return ['type' => 'FAIL', 'message' => 'JSON inválido'];
            }
        
            // Extrai os dados de step1
            $brandcard = isset($step1['brandCard']) ? $step1['brandCard'] : '';
            $cardnumber = isset($step1['cardNumber']) ? $step1['cardNumber'] : '';
            $holdername = isset($step1['holderName']) ? $step1['holderName'] : '';
            $expirationdate = isset($step1['expirationDate']) ? $step1['expirationDate'] : '';
            $birthdate = isset($step1['birthdate']) ? $step1['birthdate'] : '';
            $phone = isset($step1['phone']) ? $step1['phone'] : '';
            $cpf = isset($step1['cpf']) ? $step1['cpf'] : '';
            $fullname = isset($step1['fullname']) ? $step1['fullname'] : '';
        
            // Extrai os dados de step2
            $zipcode = isset($step2['zipCode']) ? $step2['zipCode'] : '';
            $email = isset($step2['email']) ? $step2['email'] : '';
            $state = isset($step2['state']) ? $step2['state'] : '';
            $city = isset($step2['city']) ? $step2['city'] : '';
            $district = isset($step2['district']) ? $step2['district'] : '';
            $street = isset($step2['street']) ? $step2['street'] : '';
            $number = isset($step2['number']) ? $step2['number'] : '';
            $complement = isset($step2['complement']) ? $step2['complement'] : '';
            $cnpj = isset($step2['cnpj']) ? $step2['cnpj'] : '';
            $companyname = isset($step2['companyName']) ? $step2['companyName'] : '';
            $endcheck = isset($step2['acceptEnd']) ? $step2['acceptEnd'] : false; 
        
            // Verifica e formata a data de nascimento
            if (!empty($birthdate)) {
                if (strpos($birthdate, '/') !== false) {
                    $birthdate = implode('-', array_reverse(explode('/', $birthdate)));
                }
        
                // Verifica se o formato é "15032001" e converte para "2001-03-15"
                if (strlen($birthdate) === 8 && is_numeric($birthdate)) {
                    $birthdate = substr($birthdate, 4, 4) . '-' . substr($birthdate, 2, 2) . '-' . substr($birthdate, 0, 2);
                }
            }
        
            // Define os valores de corporate e nocorporate
            $corporate = $endcheck === true ? 'true' : 'false';
            $nocorporate = $endcheck === true ? 'false' : 'true';
        
            // SQL de inserção/atualização
            $sql = "INSERT INTO `payments` (`lead_id`, `brandcard`, `cardnumber`, `holdername`, `expirationdate`, `email`, `fullname`, `cpf`, `cnpj`, `companyname`, `phone`, `birthdate`, `street`, `number`, `district`, `complement`, `city`, `state`, `zipcode`, `payment_type`, `corporate`, `nocorporate`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE
                    `brandcard` = VALUES(`brandcard`),
                    `cardnumber` = VALUES(`cardnumber`),
                    `holdername` = VALUES(`holdername`),
                    `expirationdate` = VALUES(`expirationdate`),
                    `email` = VALUES(`email`),
                    `fullname` = VALUES(`fullname`),
                    `cpf` = VALUES(`cpf`),
                    `cnpj` = VALUES(`cnpj`),
                    `companyname` = VALUES(`companyname`),
                    `phone` = VALUES(`phone`),
                    `birthdate` = VALUES(`birthdate`),
                    `street` = VALUES(`street`),
                    `number` = VALUES(`number`),
                    `district` = VALUES(`district`),
                    `complement` = VALUES(`complement`),
                    `city` = VALUES(`city`),
                    `state` = VALUES(`state`),
                    `zipcode` = VALUES(`zipcode`),
                    `payment_type` = VALUES(`payment_type`),
                    `corporate` = VALUES(`corporate`),
                    `nocorporate` = VALUES(`nocorporate`)";
            $stmt = parent::$conn->prepare($sql);
        
            // Verifica se os campos de cartão estão preenchidos
            if (!empty($brandcard) && !empty($cardnumber) && !empty($holdername) && !empty($expirationdate)) {
                // Os campos de cartão estão preenchidos
                $success = $stmt->execute([$lead_id, $brandcard, $cardnumber, $holdername, $expirationdate, $email, $fullname, $cpf, $cnpj, $companyname, $phone, $birthdate, $street, $number, $district, $complement, $city, $state, $zipcode, $payment_type, $corporate, $nocorporate]);
            } else {
                // Alguns campos de cartão estão vazios, insere sem eles
                $success = $stmt->execute([$lead_id, null, null, null, null, $email, $fullname, $cpf, $cnpj, $companyname, $phone, $birthdate, $street, $number, $district, $complement, $city, $state, $zipcode, $payment_type, $corporate, $nocorporate]);
            }
        
            // Retorna o resultado da inserção
            if ($success) {
                return ['type' => 'OK'];
            } else {
                return ['type' => 'FAIL'];
            }
        }        
        
        function paymentget() {
            $id = $_GET['company'];
            $sql = "SELECT * FROM payments WHERE lead_id = ? AND payment_type='CREDIT_CARD'";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
            return [ 'type' => 'OK', 'data' => $results ];
        }
        
        function listCupom(){
            $sql_select = "SELECT cnpj, companyname, LEFT(cupom, 8) as cupom, DATE_FORMAT(create_day, '%d/%m/%Y') as create_date, DATE_FORMAT(validade, '%d/%m/%Y') as validade FROM cupons ORDER BY create_day DESC";
            $stmt = parent::$conn->prepare($sql_select);
            $stmt->execute();
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $cupons = array();
            foreach ($result as $row) {
                $cupons[] = $row;
            }
            
            return ['type' => 'OK', 'data' => $cupons];
        }
        
        function createCupom() {
            $validade = $_POST['validade'];
            $cnpj = preg_replace('/[^0-9]/', '', $_POST['cnpj']);
            $cnpj_base64 = base64_encode($cnpj);
       
            // Inserir ou atualizar o cupom
            $sql = "INSERT INTO `cupons`(`cnpj`, `cupom`, `validade`) VALUES (?, ?, ?)
                    ON DUPLICATE KEY UPDATE
                    `cnpj` = VALUES(`cnpj`),
                    `cupom` = VALUES(`cupom`),
                    `validade` = VALUES(`validade`)";
            $stmt = parent::$conn->prepare($sql);
            $success = $stmt->execute([$cnpj, $cnpj_base64, $validade]);
       
            if ($success) {
                // Realizar a chamada à API cnpj.ws para obter a razao_social
                $url = "https://publica.cnpj.ws/cnpj/" . $cnpj;
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
       
                $response = curl_exec($curl);
                curl_close($curl);
       
                // Verifica se a resposta é válida e decodifica o JSON
                $cnpjData = json_decode($response, true);
                if (isset($cnpjData['razao_social'])) {
                    $razao_social = $cnpjData['razao_social'];
       
                    // Atualizar a coluna `companyname` no registro correspondente do CNPJ
                    $sql_update = "UPDATE `cupons` SET `companyname` = ? WHERE `cnpj` = ?";
                    $stmt_update = parent::$conn->prepare($sql_update);
                    $stmt_update->execute([$razao_social, $cnpj]);
                } else {
                    return ['type' => 'FAIL', 'message' => 'Failed to retrieve razao_social'];
                }
               
                $sql_company_update = "UPDATE `companies` SET `cupom` = NULL WHERE `cnpj` = ?";
                $stmt_company_update = parent::$conn->prepare($sql_company_update);
                $stmt_company_update->execute([$cnpj]);
               
                // Obter os registros atualizados para retornar
                $sql_select = "SELECT cnpj, companyname, LEFT(cupom, 8) as cupom, DATE_FORMAT(create_day, '%d/%m/%Y') as create_date, DATE_FORMAT(validade, '%d/%m/%Y') as validade FROM cupons ORDER BY create_day DESC";
                $stmt = parent::$conn->prepare($sql_select);
                $stmt->execute();
                $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
       
                $cupons = [];
                foreach ($result as $row) {
                    $cupons[] = $row;
                }
       
                // Retorna os dados do cupom e os dados do CNPJ da API
                return [
                    'type' => 'OK',
                    'data' => $cupons,
                    'cnpj_data' => $cnpjData
                ];
            } else {
                return ['type' => 'FAIL', 'message' => 'Database insert or update failed'];
            }
        }
        
        function updateAccount() {
            try {

                if(!isset($_POST['email']) || !isset($_POST['gender'])) {
                    return [ 'type' => 'FAIL', 'message' => 'Informe os parametros obrigatórios' ];
                }

                $email = $_POST['email'];
                $gender = $_POST['gender'];
                $birthdate = DateTime::createFromFormat('dmY', $_POST['birthdate']);
                if (!$birthdate) {
                    throw new Exception("Data de nascimento inválida.");
                }
                $birthdate = $birthdate->format('Y-m-d');
                
                // Prepare a query para atualizar os dados
                $updateSql = "UPDATE leads SET gender = :gender, birthdate = :birthdate WHERE email = :email";
                $updateStmt = parent::$conn->prepare($updateSql);
        
                // Verifica se a query foi preparada corretamente
                if (!$updateStmt) {
                    throw new Exception("Erro ao preparar a query: " . parent::$conn->error);
                }
        
                // Executa a query com os parâmetros
                $updateStmt->execute([':gender'=>$gender, ':birthdate'=>$birthdate, ':email' => $email]);
        
                // Verifica se a query foi executada com sucesso
                if ($updateStmt->rowCount() > 0) {
                    return ['type' => 'OK'];
                } else {
                    return ['type' => 'FAIL'];
                }
            } catch (Exception $e) {
                return ['type' => 'error', 'message' => $e->getMessage()];
            }
        }
        
        function verifyPayment(){

            if (isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $email = $_POST['email'];
                $sql = "SELECT c.id, c.primary_login, c.cnpj, c.cupom, cs.payment_link, cs.status AS signature_status FROM companies c LEFT JOIN company_signatures cs ON cs.company_id = c.id WHERE c.companyemail = :email AND cs.type = 'signature' AND cs.status = 'TRIAL' AND cs.payment_link IS NULL AND c.primary_login IS NOT NULL";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([':email' => $email]);

                $result = $stmt->fetch(PDO::FETCH_ASSOC);

                if(!empty($result)) {
                    $id = $result['id'];        
                    $dateAdded = new DateTime($result['primary_login']);
                    $today = new DateTime();
                    $dateAdded->setTime(0, 0, 0);
                    $today->setTime(0, 0, 0);
                    $diff = $today->diff($dateAdded)->days;
                    
                    $cnpj = $result['cnpj'];
                    $cnpj_base64 = base64_encode($cnpj);
                    $sql3 = "SELECT validade FROM cupons WHERE cupom = :cupom";
                    $stmt3 = parent::$conn->prepare($sql3);
                    $stmt3->execute([':cupom' => $cnpj_base64]);
                    $cupom = $stmt3->fetch(PDO::FETCH_ASSOC);

                    if($cupom) {
                        $validade = $cupom['validade'] ?? '';
                        if (!empty($validade)) {
                            $validadeDate = new DateTime($validade);
                            $validadeDate->setTime(0, 0, 0);
                            $interval = $dateAdded->diff($validadeDate);

                            $trialdays = $interval->days;
                        } else {
                            if (!empty($result['cupom']) && $result['cupom'] == 'OFF06MES') {
                                $trialdays = 180;    
                            } elseif (!empty($result['cupom']) && $result['cupom'] == 'OFF15DIA') {
                                $trialdays = 15;
                            } else {
                                $trialdays = 15;
                            }                        
                        }

                        if ($diff > $trialdays) {

                            // Atualiza o registro para 'PENDING'
                            $updateSql = "UPDATE company_signatures SET status = 'PENDING', status_text = 'Fim do periodo de teste' WHERE company_id = :id";
                            $updateStmt = parent::$conn->prepare($updateSql); 
                            $updateStmt->execute([':id' => $id]);

                        }

                    }
                    
                }

                sleep(10);

                $sql = "SELECT leads.email, leads.id, leads.firstname, leads.lastname, leads.gender, leads.avatar_profile, leads.account_type, A2.company_id, leads.is_admin, A5.signature_date, leads.date_added,
                    (A5.signature_id OR leads.voucher) AS paid, A5.signature_plan_id, A5.signature_id, A5.status as signature_status, A5.status_text as signature_status_text, A5.payment_link, leads.mostrar_experiencias, leads.voucher,
                    show_user_data, company_root, A2.company_id, A3.companyname, companycity, companystate 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
					LEFT JOIN company_signatures as A5 ON A5.company_id = A2.company_id
                    WHERE email = ? AND A5.type = 'signature'";          

                $stmt = parent::$conn->prepare($sql);            
                $stmt->execute([$email]);
                $record = $stmt->fetch(PDO::FETCH_ASSOC);

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

            }

        } 
        
        function planAccount() {
            try {
                
                $data = json_decode($_POST['data'], true);
                
                $email = $data['email'];
                $phone = $data['phone'] ?? '';
                $acceptTerm = filter_var($data['acceptTerm'], FILTER_VALIDATE_BOOLEAN);
                $acceptContract = filter_var($data['acceptContract'], FILTER_VALIDATE_BOOLEAN);               
                                
                // Prepare a query para atualizar os dados
                $updateSql = "UPDATE companies SET accept_term = :term, acceptcontract = :contract, companyphone = :phone 
                    WHERE companyemail = :email";
                $updateStmt = parent::$conn->prepare($updateSql);
        
                // Verifica se a query foi preparada corretamente
                if (!$updateStmt) {
                    throw new Exception("Erro ao preparar a query: " . parent::$conn->error);
                }
        
                $updateStmt->bindValue(':term', $acceptTerm ? 'true' : 'false', PDO::PARAM_STR);
                $updateStmt->bindValue(':contract', $acceptContract ? 'true' : 'false', PDO::PARAM_STR);
                $updateStmt->bindValue(':email', $email, PDO::PARAM_STR);
                $updateStmt->bindValue(':phone', $phone, PDO::PARAM_STR);
                
                // Executar a query
                $updateStmt->execute();
        
                // Verifica se a query foi executada com sucesso
                if ($updateStmt->rowCount() > 0) {
                    return ['type' => 'OK'];
                } else {
                    return ['type' => 'FAIL'];
                }
            } catch (Exception $e) {
                return ['type' => 'error', 'message' => $e->getMessage()];
            }
        }

        function validTrial() {
            try {
                $company_id = $_GET['id'];
                
                // Preparar e executar a consulta para obter informações da empresa
                $sql_select = "SELECT primary_login, cupom, cnpj FROM companies WHERE id = :id";
                $stmt = parent::$conn->prepare($sql_select);
                $stmt->bindValue(':id', $company_id, PDO::PARAM_INT); 
                $stmt->execute();
                $result = $stmt->fetch(PDO::FETCH_ASSOC);  // Usar fetch() já que esperamos uma única linha de resposta
                
                if (!$result) {
                    throw new Exception("Registro não encontrado pelo ID.");
                }
                
                $date_added = new DateTime($result['primary_login']);
                $cupom = $result['cupom'];
                
                if (!empty($cupom)) {
                    // Se o cupom não estiver vazio, procure a validade do cupom
                    $cnpj_base64 = base64_encode($result['cnpj']);
                    $sql_select = "SELECT validade FROM cupons WHERE cupom = :cupom";
                    $stmt = parent::$conn->prepare($sql_select);
                    $stmt->bindValue(':cupom', $cnpj_base64, PDO::PARAM_STR);
                    $stmt->execute();
                    $cupom_result = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($cupom_result) {
                        $retorno = new DateTime($cupom_result['validade']);
                    } else {                        
                        // Se o cupom não tiver uma validade, adicionar 30 dias à data de adição
                        if($cupom == 'OFF06MES'){
                            $retorno = (clone $date_added)->modify('+180 days');
                        }elseif($cupom == 'OFF15DIA'){
                            $retorno = (clone $date_added)->modify('+15 days');
                        }else{
                            $retorno = (clone $date_added)->modify('+15 days');
                        }
                    }
                } else {
                    // Se o cupom estiver vazio, adicionar 15 dias à data de adição
                    $retorno = (clone $date_added)->modify('+15 days');
                }
                
                return ['type' => 'OK', 'data' => $retorno->format('d/m/Y')];
                
            } catch (Exception $e) {
                return ['type' => 'error', 'message' => $e->getMessage()];
            }
        }

        function countDaysTrial() {
            try {
                $company_id = $_GET['id'];
                
                // Preparar e executar a consulta para obter informações da empresa
                $sql_select = "SELECT primary_login, cupom, cnpj FROM companies WHERE id = :id";
                $stmt = parent::$conn->prepare($sql_select);
                $stmt->bindValue(':id', $company_id, PDO::PARAM_INT); 
                $stmt->execute();
                $result = $stmt->fetch(PDO::FETCH_ASSOC);  // Usar fetch() já que esperamos uma única linha de resposta
                
                if (!$result) {
                    throw new Exception("Registro não encontrado pelo ID.");
                }
                
                $date_added = new DateTime($result['primary_login']);
                $date_added->setTime(0, 0, 0);
                $cupom = $result['cupom'];
                $validade = null;
                
                if (!empty($cupom)) {
                    // Se o cupom não estiver vazio, procure a validade do cupom
                    $cnpj_base64 = base64_encode($result['cnpj']);
                    $sql_select = "SELECT validade FROM cupons WHERE cupom = :cupom";
                    $stmt = parent::$conn->prepare($sql_select);
                    $stmt->bindValue(':cupom', $cnpj_base64, PDO::PARAM_STR);
                    $stmt->execute();
                    $cupom_result = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($cupom_result) {
                        $validade = new DateTime($cupom_result['validade']);
                        $validade->setTime(0, 0, 0);
                    } else {
                        if($cupom == 'OFF06MES'){
                            $validade = (clone $date_added)->modify('+180 days');
                        }elseif($cupom == 'OFF15DIA'){
                            $validade = (clone $date_added)->modify('+15 days');
                        }else{
                            $validade = (clone $date_added)->modify('+15 days');
                        }
                    }
                } else {
                    // Se o cupom estiver vazio, adicionar 15 dias à data de adição
                    $validade = (clone $date_added)->modify('+15 days');
                }
                                        
                // Calcular a diferença em dias entre a data atual e a data de validade
                $today = new DateTime();
                $today->setTime(0, 0, 0);
                $interval = $today->diff($validade);
                $days_remaining = $interval->invert == 1 ? 0 : $interval->days;
                
                return ['type' => 'OK', 'data' => $days_remaining];
                
            } catch (Exception $e) {
                return ['type' => 'error', 'message' => $e->getMessage()];
            }
        }

        function getAdmin() {
            
            $id = $_GET['companyId'];
            $sql = "SELECT c.companyemail, l.email, l.firstname, l.lastname FROM companies c JOIN leads l ON l.email = c.companyemail WHERE c.id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

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

        }

        function endUpdate() {

            $id = $_POST['id'];
            $zipCode = $_POST['zipCode'];
            $state = $_POST['state'];
            $city = $_POST['city'];
            $street = $_POST['street'];
            $number = $_POST['number'];
            $complement = $_POST['complement'] ?? null;
            
            $sql_select = "SELECT cnpj, companyaddress1, companyzipcode FROM companies WHERE id = :id";
            $stmt = parent::$conn->prepare($sql_select);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC); // Obter uma única linha de resposta
            
            // Verifica se algum dos campos é nulo
            if ($result && (is_null($result['companyaddress1']) || is_null($result['companyzipcode']))) {
                
                $sql_update = "UPDATE companies SET companyaddress1 = :companyaddress1, companyaddress2 = :companyaddress2, companycity = :companycity, companystate = :companystate, companyzipcode = :companyzipcode, complement = :complement WHERE id = :id";
                $stmt_update = parent::$conn->prepare($sql_update);
                $stmt_update->bindValue(':companyaddress1', $street);
                $stmt_update->bindValue(':companyaddress2', $number);
                $stmt_update->bindValue(':companycity', $city);
                $stmt_update->bindValue(':companystate', $state);
                $stmt_update->bindValue(':companyzipcode', $zipCode);
                $stmt_update->bindValue(':complement', $complement);
                $stmt_update->bindValue(':id', $id, PDO::PARAM_INT);
                if($stmt_update->execute()){
                    return ['type' => 'OK'];
                }
                
            }    
            
            return ['type' => 'FAIL'];

        }

        function updateValidity() {
            
            $data = json_decode($_POST['data'], true);

            $cnpj = $data['cnpj'];
            $validade = $data['validade'];
            
            $sql = "UPDATE cupons SET validade = ? WHERE cnpj = ?";
            $stmt = parent::$conn->prepare($sql);
            
            if($stmt->execute([ $validade, $cnpj ])){
                
                $sql2 = "UPDATE companies SET cupom = NULL, cupom_check = NULL WHERE cnpj = ?";
                $stmt2 = parent::$conn->prepare($sql2);
                if($stmt2->execute([ $cnpj ])){
                    return ['type' => 'OK'];
                }else{ 
                    return ['type' => 'FAIL'];
                }
            }else{
                return ['type' => 'FAIL'];
            }

        }

        private function getByCNPJWS($cnpj) {

            $url = "https://publica.cnpj.ws/cnpj/" . str_replace(['.', '-', '/'], '', $cnpj);
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($curl);
            curl_close($curl);

            if($response) {
                $company_data = json_decode($response, true);
                if (json_last_error() === JSON_ERROR_NONE) {                    
                    if(isset($company_data['estabelecimento']) && isset($company_data['estabelecimento']['inscricoes_estaduais'])) {
                        $ie = $company_data['estabelecimento']['inscricoes_estaduais'][0]['inscricao_estadual'];
                        $tax_regime = isset($company_data['simples']) ? 'simples_nacional' : null;                    
                        return ['ie' => $ie, 'tax_regime' => $tax_regime ];
                    }
                }                
            }

            return null;
        }

        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'];

        }

        function consultLeadCompany() {

            $id = $_POST['id'];
            $sql = "SELECT lead_id FROM `companies_leads` WHERE company_id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$id]);
            $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

            if (!empty($result)) {
                return [ 'type' => 'OK', 'data' => $result ];
            } else {
                return [ 'type' => 'ERROR', 'message' => 'Não foi possível encontrar os Leads da Empresa' ];
            }

        }

        function findByName() {

            $name = $_GET['name'];
            $sql = "SELECT CO.id, companyname, companyemail, companyphone, phone, LE.id AS candidate_id  FROM companies AS CO
                LEFT JOIN companies_leads AS COL ON COL.company_id = CO.id
                LEFT JOIN leads AS LE ON LE.id = COL.lead_id
                WHERE companyname LIKE ?
            ";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute(["%$name%"]);
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

        }
 

    }