<?php
include_once __dir__ .  '/../core/LogEvent.php';
    
class InvitationMessage extends Core {

    function getInvitationMessage() {

        if (!isset($_GET['companyId']) || !is_numeric($_GET['companyId'])) {
            throw new Exception('Parâmetro companyId inválido ou ausente.');
        }
        if (!isset($_GET['processId']) || !is_numeric($_GET['processId'])) {
            throw new Exception('Parâmetro processId inválido ou ausente.');
        }
        $company_id = (int)$_GET['companyId'];
        $process_id = (int)$_GET['processId'];
        $message = null;

        $sql = "SELECT invite_message FROM process_list WHERE id = :process_id AND invite_message IS NOT NULL";
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindParam(':process_id', $process_id, PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if($result) {
            $message = $result['invite_message'];
            return [
                'message' => $message
            ];
        }

        $sql = "SELECT default_invite_message FROM companies WHERE id = :company_id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindParam(':company_id', $company_id, PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        $message = $result['default_invite_message'];
        return [
            'message' => $message
        ];

    }
    
    function saveInvitationMessage() {

        if (!isset($_POST['processId']) || !is_numeric($_POST['processId'])) {
            throw new Exception('Parâmetro id inválido ou ausente.');
        }
        if (!isset($_POST['message']) || !is_string($_POST['message']) || trim($_POST['message']) === '') {
            throw new Exception('Parâmetro invite_message inválido ou ausente.');
        }

        $id = (int)$_POST['processId'];        
        $invite_message = trim($_POST['message']);
        $user_id = $_POST['userId'];
        $lead_id = $_POST['leadId'];

        $sql = "UPDATE process_list SET invite_message = :invite_message WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->bindParam(':invite_message', $invite_message, PDO::PARAM_STR);
        $stmt->execute();

        $sql = "SELECT * FROM leads WHERE id = :lead_id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindParam(':lead_id', $lead_id, PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $name = strtoupper($result['firstname'] . ' ' . $result['lastname']);
        $insert_id = $result['id'];
        $title = "Convite enviado via whatsapp para $name";
        $url = "/recruiter/process";
        
        LogEvent::log($user_id, $insert_id, $url, $title, LogEvent::SEND_WHATSAPP);

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

    }

}