<?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);

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

        }

        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'];
            $site = $_POST['site'];
            $facebook = $_POST['facebook'];
            $instagram = $_POST['instagram'];
            $youtube = $_POST['youtube'];
            $website = $_POST['website'];
            
            $sql = "UPDATE companies 
                SET companyname = :companyname, companyaddress1 = :companyaddress1, companyaddress2 = :companyaddress2,
                    companycity = :companycity, companystate = :companystate, companyzipcode = :companyzipcode,
                    companywebsite = :companywebsite,
                    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,
                ':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;

            $sql = "SELECT * FROM companies LIMIT :offset, :limit";
            $stmt = parent::$conn->prepare($sql);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
            $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 ? 'email' : 'id';
            $sql = "SELECT email, cupom FROM leads 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 leads SET 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 = "DELETE FROM leads WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $id_user ]);
            
            $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'];
            $email = $_POST['email'];
            $cpf = $_POST['cpf'];
            $cnpj = $_POST['cnpj'];
            $companyname = $_POST['companyName'];
            $phone = $_POST['phone'];
            $birthdate = $_POST['birthdate'];
            $fullname = $_POST['fullname'];
            $street = $_POST['street'];
            $number = $_POST['number'];
            $district = $_POST['district'];
            $complement = $_POST['complement'];
            $city = $_POST['city'];
            $state = $_POST['state'];
            $zipcode = $_POST['zipCode'];
            $payment_type = $_POST['payment_type'];
            $endcheck = $_POST['acceptEnd'];
            $brandcard = $_POST['brandCard'];
            $cardnumber = $_POST['cardNumber'];
            $holdername = $_POST['holderName'];
            $expirationdate = $_POST['expirationDate'];
        
            // Verifica e formata a data de nascimento
            if (!empty($birthdate)) {
                if (strpos($birthdate, '/') !== false) {
                    $birthdate = implode('-', array_reverse(explode('/', $birthdate)));
                }
        
                // Verifica se o formato é "15022001" e converte para "2001-02-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 = isset($endcheck) && $endcheck === "true" ? 'true' : 'false';
            $nocorporate = isset($endcheck) && $endcheck === "true" ? 'false' : 'true';
        
            $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 listCupom(){
            $sql_select = "SELECT cnpj, 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 id 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];
            //return ['type' => 'OK'];
        }
        
        function createCupom(){
            
            $validade = $_POST['validade'];
            
            $cnpj = preg_replace('/[^0-9]/', '', $_POST['cnpj']);
            $cnpj_base64 = base64_encode($cnpj);
            
            $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]);
        
            // Retorna o resultado da inserção
            if ($success) {
                
                $sql_select = "SELECT cnpj, 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 id 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];
                
            } else {
                return ['type' => 'FAIL'];
            }
            
        }

    }