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

class FitCultural extends Core
{

    private function getPostData($key, $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        return filter_input(INPUT_POST, $key, $filter);
        return $order;
    }

    private function getGetData($key, $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        return filter_input(INPUT_GET, $key, $filter);
    }

    function listAll()
    {
        $company_id = $_GET['companyId'];
        $white_lb_id = $this->config['WHITE_LABEL_ID'];

        $sql = "SELECT FC.*, L.firstname, L.lastname FROM fit_cultural AS FC 
            LEFT JOIN leads AS L ON L.id = FC.lead_id
            WHERE company_employee_id = :company_employee_id AND FC.white_label_id = :white_label_id ORDER BY data_init_fit DESC";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute(['company_employee_id' => $company_id, 'white_label_id' => $white_lb_id]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    function list()
    {
        $user_id = isset($_GET['userId']) ? $_GET['userId'] : null;
        $email = $_GET['email'];
        // Corrigido o SQL para fechar a aspas após o nome da tabela.
        $sql = "SELECT * FROM `fit_cultural` WHERE lead_id = ?";
        // Usando a conexão correta através do parent::$conn
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$user_id]);
        $results =  $stmt->fetchAll(PDO::FETCH_ASSOC);

        if(sizeof($results) && $user_id) {

            $sql = "SELECT id, firstname FROM leads WHERE email = ?";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$email]);
            $lead = $stmt->fetch(PDO::FETCH_ASSOC);

            $title = "Acessou o fit cultural \"{$lead['firstname']}\"";
            $url = "";            
            LogEvent::log($user_id, $lead['id'], $url, $title, LogEvent::VIEW_FIT_CULTURAL);

        }

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

    function save()
    {
        
        if (isset($_POST['email']) && isset($_POST['data_init']) && !empty($_POST['data_init'])) {
            $lead_id = $_POST['lead_id'];
            $email = $_POST['email'];
            $pergunta = $_POST['pergunta'];
            $resposta = $_POST['resposta'];
            $data_init = date('Y-m-d', strtotime($_POST['data_init']));
            $white_lb_id = $this->config['WHITE_LABEL_ID'];
            // Consulta para verificar se o e-mail já existe
            $stmt = parent::$conn->prepare("
                SELECT id_fit 
                FROM fit_cultural 
                WHERE email_fit = :email OR lead_id = :id
            ");
            $stmt->bindParam(':email', $email, PDO::PARAM_STR);
            $stmt->bindParam(':id', $lead_id);

            if ($stmt->execute()) {

                if ($stmt->rowCount() > 0) {
                    // Se o e-mail já existe, atualize a resposta e a data
                    $sql = "
                        UPDATE `fit_cultural` 
                        SET `pergunta" . $pergunta . "_fit` = :resposta, `data_init_fit` = :data_init, `lead_id` = :lead_id, `white_label_id` = :white_label_id
                        WHERE email_fit = :email OR lead_id = :lead_id
                    ";
                } else {
                    // Se o e-mail não existe, insira a nova resposta e a data
                    $sql = "
                        INSERT INTO `fit_cultural`(`lead_id`, `email_fit`, `pergunta" . $pergunta . "_fit`, `data_init_fit`, `white_label_id`)
                        VALUES (:lead_id, :email, :resposta, :data_init, :white_label_id)
                    ";

                    $insert_id = parent::$conn->lastInsertId();
                    $title = "Preenchimento do Fit Cultural realizado";
                    $url = "/recruiter/fitcultural";
                    LogEvent::log($lead_id, $insert_id, $url, $title, LogEvent::FILL_FIT_CULTURAL, true);

                }

                $stmt = parent::$conn->prepare($sql);

                $stmt->bindParam(':lead_id', $lead_id, PDO::PARAM_STR);
                $stmt->bindParam(':email', $email, PDO::PARAM_STR);
                $stmt->bindParam(':resposta', $resposta, PDO::PARAM_STR);
                $stmt->bindParam(':data_init', $data_init, PDO::PARAM_STR);
                $stmt->bindParam(':white_label_id', $white_lb_id, PDO::PARAM_STR);

                if ($stmt->execute()) {
                    $responseData['msg'] = "Resposta registrada com sucesso";
                } else {
                    $responseData['msg'] = "Ocorreu um erro ao registrar a resposta";
                }
            } else {
                $responseData['msg'] = "Ocorreu um erro ao consultar o fit";
            }
        } else {
            $responseData['msg'] = "E-mail ou data inválidos";
        }
        
        return $responseData;
    }

    function requestFilling()
    {
        $lead_id = $this->getPostData('leadId');
        $process_id = $this->getPostData('processId');
        $user_id = $this->getPostData('userId');
        $sql = "INSERT INTO fit_cultural_request(lead_id, process_id, user_id) VALUES(:lead_id, :process_id, :user_id)";

        $stmt = parent::$conn->prepare($sql);

        if ($stmt->execute([
            ':lead_id' => $lead_id,
            ':process_id' => $process_id,
            ':user_id' => $user_id
        ])) {

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

            $title = "Foi solicitada a participação de $name no preenchimento do Fit Cultural.";
            $url = "/recruiter/process";
            
            LogEvent::log($user_id, $lead_id, $url, $title, LogEvent::REQUEST_FILLING_FILL);

            return ['type' => 'OK'];
        } else {
            return ['type' => 'Error', 'message' => 'Failed to execute query'];
        }
    }

    function getRequestedFilling()
    {

        $lead_id = $this->getGetData('leadId');
        $process_id = $this->getGetData('processId');

        $sql = "SELECT * FROM fit_cultural_request WHERE lead_id = :lead_id AND process_id = :process_id ORDER BY id DESC LIMIT 1";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':lead_id' => $lead_id,
            ':process_id' => $process_id
        ]);

        return [
            'type' => 'OK',
            'result' => $stmt->fetch(PDO::FETCH_ASSOC)
        ];
    }
}
