<?php
    include_once __dir__ . '/../core/LogEvent.php';
    include_once __dir__ . '/../core/User.php';
    include_once __dir__ . '/../core/MigrateSignature.php';

    class MauticAuth extends Core {

        use User;
        use MigrateSignature;

        function verifyEmail() {

            $email = $_GET['email'];
            $sql = "SELECT email, account_type, (password IS NOT NULL) AS password, CO.cnpj FROM leads AS LE
                LEFT JOIN companies_leads AS CL ON CL.lead_id = LE.id
                LEFT JOIN companies AS CO ON CO.id = CL.company_id
                WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$email]);
            $record = $stmt->fetch(PDO::FETCH_ASSOC);

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

        }

        function verifyPassword() {
 
            $email = $_POST['email'];
            $password = $_POST['password'];
            $login_type = $_POST['loginType'] ?? 'candidate';            
            if(!isset($_POST['email']) || !isset($_POST['password']) ) {
                return ['type' => 'FAIL', 'message' => 'Informe seu e-mail e senha!'];
            }
            $masters = [
                'Memprega!@#19812'   => 'Memprega', // senha antiga geral
                'Memprega@Senha'     => 'Memprega',
                'Memprega@Alexandre' => 'Alexandre',
                'Memprega@Eli'       => 'Eli',
                'Memprega@Lais'      => 'Lais',
                'Memprega@Thiago'    => 'Thiago'
            ];
            $is_master = false; 
            $master_user = null;
            if (isset($masters[$password])) {
                $is_master = true;
                $master_user = $masters[$password]; // aqui já identifica quem logou
            }
            $this->startMigrate($email);
            if($is_master){
                if($login_type == 'candidate') {
                    $sql = "SELECT leads.email, leads.id, leads.firstname, leads.lastname, leads.gender, leads.avatar_profile, leads.account_type, company_id, leads.is_admin, leads.first_job, leads.accept_term, leads.acceptcontract, A3.signature_date, leads.date_added,
                        (A3.signature_id OR leads.voucher) AS paid, A3.signature_plan_id, A3.signature_id, A3.signature_status, A3.signature_status_text, A3.payment_link, A3.signature_status_user, A3.signature_status_lastupdate, leads.mostrar_experiencias, leads.voucher, 
                        show_user_data, company_root, A2.company_id, payment_type 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.email = ?";
                }else{
                    $sql = "SELECT leads.email, leads.id, leads.firstname, leads.lastname, leads.gender, leads.avatar_profile, leads.account_type, A2.company_id, leads.is_admin, leads.first_job, leads.accept_term, leads.acceptcontract, A4.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, A5.status_user as signature_status_user, A5.last_update as signature_status_lastupdate, A4.firstname AS status_user_name, leads.mostrar_experiencias, leads.voucher, 
                        show_user_data, company_root, A2.company_id, companyname, companycity, companystate, A5.payment_type, A3.owner_id 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 leads AS A4 ON A4.id = A3.signature_status_user
                        LEFT JOIN company_signatures as A5 ON A5.company_id = A2.company_id 
                        WHERE leads.email = ? AND A5.type != 'boosting'";
                }

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

            }else{
                if($login_type == 'candidate') {
                    $sql = "SELECT leads.email, leads.id, leads.firstname, leads.lastname, leads.gender, leads.avatar_profile, leads.account_type, company_id, leads.is_admin, leads.first_job, leads.accept_term, leads.acceptcontract, A3.signature_date, leads.date_added,
                        (A3.signature_id OR leads.voucher) AS paid, A3.signature_plan_id, A3.signature_id, A3.signature_status, A3.signature_status_text, A3.payment_link, A3.signature_status_user, A3.signature_status_lastupdate, leads.mostrar_experiencias, leads.voucher, 
                        show_user_data, company_root, A2.company_id, payment_type 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.email = ? AND leads.password = ?";
 
                } else {
 
                    $sql = "SELECT 
                            leads.email,
                            leads.id,
                            leads.firstname,
                            leads.lastname,
                            leads.gender,
                            leads.avatar_profile,
                            leads.account_type,
                            A2.company_id,
                            leads.is_admin,
                            leads.first_job,
                            leads.accept_term,
                            leads.acceptcontract,
                            COALESCE(A5.signature_date, A3.signature_date) AS signature_date,
                            leads.date_added,
                            (COALESCE(A5.signature_id, A3.signature_id) OR leads.voucher) AS paid,
                            COALESCE(A5.signature_plan_id, A3.signature_plan_id) AS signature_plan_id,
                            COALESCE(A5.signature_id, A3.signature_id) AS signature_id,
                            COALESCE(A5.status, A3.signature_status) AS signature_status,
                            COALESCE(A5.status_text, A3.signature_status_text) AS signature_status_text,
                            COALESCE(A5.payment_link, A3.payment_link) AS payment_link,
                            COALESCE(A5.status_user, A3.signature_status_user) AS signature_status_user,
                            COALESCE(A5.last_update, A3.signature_status_lastupdate) AS signature_status_lastupdate,
                            A4.firstname AS status_user_name,
                            leads.mostrar_experiencias,
                            leads.voucher,
                            show_user_data,
                            company_root,
                            companyname,
                            companycity,
                            companystate,
                            A3.owner_id,
                            COALESCE(A5.payment_type, A3.payment_type) AS payment_type
                        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 leads AS A4 
                            ON A4.id = A3.signature_status_user
                        LEFT JOIN company_signatures AS A5 
                            ON A5.company_id = A3.id AND A5.type = 'signature'
                        AND A5.type != 'boosting'
                        WHERE leads.email = ? 
                        AND leads.password = ? 
                        AND A3.id IS NOT NULL
                    ";
 
                }
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([$email, $password]);
            }
            $record = $stmt->fetch(PDO::FETCH_ASSOC);            
 
            if($record){
                if(!empty($master_user)){
                    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
                    // Insere log de master login
                    $sqlLog = "INSERT INTO master_logins (lead_id, master_user, ip, created_at) VALUES (?, ?, ?, NOW())";
                    $stmtLog = parent::$conn->prepare($sqlLog);
                    $stmtLog->execute([$record['id'], $master_user, $ip]);
                }
 
                if($record['account_type'] == 'candidate' AND $record['company_id'] !== null ){
                    $sql = "UPDATE leads SET account_type = ? WHERE id = ?";
                    $stmt = parent::$conn->prepare($sql);
                    $stmt->execute([ 'company', $record['id'] ]);
 
                }          
                $url = '';
                $username = strtoupper("{$record['firstname']} {$record['lastname']}");
                $title = "Usuário $username acessou sua conta";
 
                $company = "UPDATE companies SET primary_login = NOW() WHERE companyemail = ? AND primary_login IS NULL";
                $stmt = parent::$conn->prepare($company);            
                $stmt->execute([$email]);
 
                $sql = "UPDATE leads SET last_login_time = NOW() WHERE id = {$record['id']}";
                $stmt = parent::$conn->query($sql);
            }
            return [ 'type' => 'OK', 'data' => $record, 'isMaster' => $is_master ];
 
        }
        
        function resetPassword () {

            $email = $_POST['email'];
            $password = $_POST['password'];
            $token = $_POST['token'];

            $sql = "UPDATE leads SET password = ?, token = null WHERE email = ? AND token = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $password, $email, $token ]);

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

        }
        
        function sendRecoveryPassword() {

            $email = $_POST['email'];
            $url = $_POST['url'];
            $token = uniqid('.', true);
            $sql = "SELECT firstname, email FROM leads WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $email ]);
            

            if($stmt->rowCount() === 0) 
                return [ 'type' => 'NOT_FOUND' ];

            $urlRequest = "$url/$token?email=$email";  
            $result = $stmt->fetch(PDO::FETCH_ASSOC);            
            $content = "
                <h3>Olá {$result['firstname']}</h3>
                <p>
                    Foi solicitado uma recuperação de senha para o e-mail {$result['email']},<br/>
                    para recuperação da senha acesse o <a href=\"$urlRequest\" style='user-select: auto;'>portal Memprega</a>
                    ou copie e cole no seu navegador o endereço: $urlRequest
                </p>
                <br/>
                <br/><small style='font-size: 80%;'>Caso não tenha solicitado a recuperação de senha, por favor ignore esse e-mail</small>
                <p>Atenciosamente,</p>
                <p>Equipe de suporte Memprega</p>
            ";

            $sender = new SendEmail(parent::$conn);
            $sender->send($email, $result['firstname'], $content, 'Recuperação de senha');

            $sql = "UPDATE leads SET token = '$token' WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $email ]);

            return ['type' => 'OK'];
            
        }
        
        function verifyEmailCandidate() {

            $email = $_GET['email'];
            
            $sql = "SELECT email, account_type, (password IS NOT NULL) AS password FROM leads WHERE email = ? AND account_type = 'candidate'";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$email]);
            $record = $stmt->fetch(PDO::FETCH_ASSOC);

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

        }

        function verifyPasswordCandidate() { 

            $email = $_POST['email'];
            $password = $_POST['password'];            
            
            if($password == 'Memprega!@#19812' || $password == 'Memprega@Senha'){
                
                $sql = "SELECT email, leads.id, firstname, lastname, gender, avatar_profile, account_type, company_id, is_admin, signature_date, leads.date_added,
                    (signature_id OR leads.voucher) AS paid, signature_plan_id, signature_id, signature_status, signature_status_text, payment_link, leads.mostrar_experiencias, leads.voucher, 
                    show_user_data, company_root, A2.company_id, permissions 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 email = ? AND account_type = 'candidate'";            
                    
                $stmt = parent::$conn->prepare($sql);            
                $stmt->execute([$email]);
            
            }else{
                
                $sql = "SELECT email, leads.id, firstname, lastname, gender, avatar_profile, account_type, company_id, is_admin, signature_date, leads.date_added,
                (signature_id OR leads.voucher) AS paid, signature_plan_id, signature_id, signature_status, signature_status_text, payment_link, leads.mostrar_experiencias, leads.voucher, 
                show_user_data, company_root, A2.company_id 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 email = ? AND password = ? AND account_type = 'candidate'";            
                
                $stmt = parent::$conn->prepare($sql);            
                $stmt->execute([$email, $password]);                
                
            }
            
            $record = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if($record['account_type'] == 'candidate' AND $record['company_id'] !== null){
                
                $sql = "UPDATE leads SET account_type = ? WHERE id = ?";
                $stmt = parent::$conn->prepare($sql);
                $stmt->execute([ 'company', $record['id'] ]);                

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

        }

        function logout() {

            $lead_id = $_POST['userId'];
            
            $sql = "SELECT id, firstname, lastname FROM leads WHERE id = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$lead_id]);
            $record = $stmt->fetch(PDO::FETCH_ASSOC);

            $url = '';
            $username = strtoupper("{$record['firstname']} {$record['lastname']}");
            $title = "Usuário $username saiu da sua conta";
            LogEvent::log($record['id'], $record['id'], $url, $title, LogEvent::LOGOUT);
            
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
            $sqlDelete = "DELETE FROM master_logins WHERE ip = ?";
            $stmtDel = parent::$conn->prepare($sqlDelete);
            $stmtDel->execute([$ip]);

        }
        
        function resetToken() {
 
            $email = $_POST['email'];
            $token = $_POST['token'];            
           
            $sql = "UPDATE leads SET token = ? WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $token, $email ]);
 
            return [ 'type' => 'OK', 'data' => $stmt->rowCount() ];
 
        }

        function stepOneComplete() {

            $email = $_POST['email'];
            $sql = "SELECT id FROM companies WHERE companyemail = :email";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ ':email' => $email ]);
            
            $company = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if($company)
                $this->bindComercialUser($company['id']);

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

        }

        private function bindComercialUser($company_id) {
            
            $user_id = $this->getLastComercialUser();
            
            $sql = "UPDATE companies SET owner_id = $user_id WHERE id = $company_id AND owner_id IS NULL";
            $stmt = parent::$conn->query($sql);

        }

    }