<?php

class ProcessListAction extends Core
{

    const SEGMENTS = [
        'viewed.paid' => 21,
        'viewed.unpaid' => 23,
        'selected.paid' => 24,
        'selected.unpaid' => 25,
        'interview' => 20,
        'interview.unpaid' => 22,
        'test.paid' => 27,
        'test.unpaid' => 28,
        'voucher' => 26
    ];

    function save()
    {

        $process_list = $_POST['processList'];
        $leads = $_POST['leads'];
        $action = $_POST['action'];
                
        // Validação dos parâmetros do POST
        if (empty($process_list) || !is_numeric($process_list)) {
            return ['type' => 'ERROR', 'message' => 'Invalid or missing process list ID'];
        }

        if (empty($leads)) {
            return ['type' => 'ERROR', 'message' => 'Leads parameter is required'];
        }

        // if (empty($action) || !array_key_exists($action, self::SEGMENTS)) {
        //     return ['type' => 'ERROR', 'message' => 'Invalid or missing action'];
        // }

        // Função para formatar leads
        function formatLeads($leads)
        {
            // Se leads é uma string JSON
            if (is_string($leads)) {
                // Verifica se é um JSON válido
                $decodedLeads = json_decode($leads, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    // Se é um array de objetos com a chave 'id'
                    if (isset($decodedLeads[0]['id'])) {
                        return array_map(function ($item) {
                            return ['id' => $item['id']];
                        }, $decodedLeads);
                    }
                    // Se é um array de IDs diretos
                    return array_map(function ($item) {
                        return ['id' => $item];
                    }, $decodedLeads);
                }
            }

            // Se leads é uma string com IDs separados por vírgulas
            if (strpos($leads, ',') !== false) {
                $ids = explode(',', $leads);
                return array_map(function ($id) {
                    return ['id' => trim($id)];
                }, $ids);
            }

            // Se leads é um único ID ou não está em JSON
            return [['id' => trim($leads)]];
        }

        $leads = formatLeads($leads);

        $sql = "INSERT INTO process_list_lead_actions(action, lead, process_list) VALUES(?, ?, ?) 
            ON DUPLICATE KEY UPDATE frequency = frequency + 1, last_update = NOW()";

        $campaign = new QueueCampaign($this->getConnection());
        $candidates_email = array();

        foreach ($leads as $lead) {
            $lead_id = $lead['id']; // Pegue o valor do 'id'

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([$action, $lead_id, $process_list]);
            if ($action !== 'searched') {
                $candidates_email[] = array('lead' => $lead_id);
                $campaign->queue($lead_id, $action);
            }
        }

        if (sizeof($candidates_email)) {
            $sender = new SendEmail($this->getConnection());
            foreach ($candidates_email as $email)
                $sender->sendForProcessList($email['lead'], $action, [], $process_list, $action !== 'searched');
        }

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

    function list()
    {

        $lead = $_GET['id'];
        $sql = "SELECT count(*) as total, action, last_update FROM process_list_lead_actions WHERE lead = ? GROUP BY action";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$lead]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

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