<?php

define("ID_CONTA", "201007");
define("TOKEN_LOCAWEB", "qAxRMhZkrdcW4CQDG9yi5rxBoyNBpqobEeQgwbmSzuQr");
define("TEMPLATE_ID", "2");
define("LIST_NAME", "Lista Automática API");
define("DOMAIN_ID", "220305");

class LocaWeb extends Core {

    function enviarEmailLocawebAPI() {

        $apiToken = TOKEN_LOCAWEB;
        $listName = LIST_NAME; 
        $templateId = TEMPLATE_ID;
        $lead_ids = !empty($_POST['lead_ids']) ? json_decode($_POST['lead_ids']) : [];
        $assunto = $_POST['subject'];

        $variaveisGlobais = [];
        
        
        if (!empty($_POST['title'])) {
            $variaveisGlobais['Titulo'] = $_POST['title'] ?? $_POST['subject'];
        }
        
        if (!empty($_POST['message'])) {
            $variaveisGlobais['Mensagem'] = "<p> Olá Prezado(a), </p>".$_POST['message'];
        }

        $baseUrl = 'https://emailmarketing.locaweb.com.br/api/v1';
        $headers = [
            "Content-Type: application/json",
            "X-Auth-Token: " . $apiToken
        ];

        // =========================
        // 1. Montar lista de contatos
        // =========================
        $emails = [];
        foreach ($lead_ids as $lead_id) {            
            $sqlLead = "SELECT CONCAT(firstname, ' ', lastname) AS fullname, email FROM leads WHERE id = ?";
            $stmtLead = parent::$conn->prepare($sqlLead);
            $stmtLead->execute([$lead_id]);
            $lead = $stmtLead->fetch(PDO::FETCH_ASSOC);
            if (!$lead || empty($lead['email'])) {
                continue;
            }
            $emails[] = [
                'email' => trim($lead['email']),
                'name' => $lead['fullname']
            ];
        }

        if (empty($emails)) {
            throw new Exception("Nenhum lead válido encontrado para envio.");
        }

        // =========================
        // 2. Buscar ou criar lista
        // =========================
        $urlList = "$baseUrl/accounts/".ID_CONTA."/lists";

        $ch = curl_init($urlList);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,               // para retornar cabeçalhos
            CURLOPT_FAILONERROR => false,         // não falhar automático no HTTP >=400
        ]);
        $responseWithHeader = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($responseWithHeader, 0, $headerSize);
        $body   = substr($responseWithHeader, $headerSize);
        
        curl_close($ch);
        
        // file_put_contents(
        //     "LOCAWEB_DEBUG_LIST_FULL.TXT",
        //     "URL chamada: $urlList\n".
        //     "HTTP Status: $httpCode\n".
        //     "Cabeçalhos:\n$header\n".
        //     "Body:\n$body\n\n",
        //     FILE_APPEND
        // );
        
        // Decodifica depois
        $listas = json_decode($body, true);

        // Garante que estamos lidando com um array de listas
        if (isset($listas['items']) && is_array($listas['items'])) {
            $listas = $listas['items'];
        }
        
        // Busca a lista pelo nome
        $listId = null;
        if (is_array($listas)) {
            foreach ($listas as $lista) {
                if (is_array($lista) && isset($lista['name']) && strcasecmp($lista['name'], $listName) === 0) {
                    $listId = $lista['id'];
                    break;
                }
            }
        }

        // Criar lista se não existir
        if (!$listId) {
            $ch = curl_init($urlList);
            curl_setopt_array($ch, [
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode(["name" => $listName])
            ]);
            $response = curl_exec($ch);
            $data = json_decode($response, true);
            curl_close($ch);
            $listId = $data['id'] ?? null;
        }
        
        // file_put_contents(
        //     "LOCAWEB_DEBUG_LIST.TXT",
        //     "Resposta bruta da API de listas:\n" . print_r($response, true) . "\n\n".
        //     "Listas decodificadas Busca:\n" . print_r($listas, true) . "\n\n".
        //     "Listas decodificadas Nova:\n" . print_r($data, true) . "\n\n".
        //     "List ID detectado: $listId\n",
        //     FILE_APPEND
        // );

        if (!$listId) {
            throw new Exception("❌ Não foi possível criar ou localizar a lista.");
        }

        // =========================
        // 3. Limpar contatos existentes
        // =========================
        $this->limparContatosLista($listId, $headers, $baseUrl);

        // =========================
        // 4. Importar novos contatos
        // =========================
        $urlContacts = "$baseUrl/accounts/".ID_CONTA."/lists/$listId/contacts";
        $contactsPayload = array_map(function ($item) {
            return [
                "email" => $item['email'],
                "name"  => $item['name'],
                "status" => "active"
            ];
        }, $emails);

        $ch = curl_init($urlContacts);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(["contacts" => $contactsPayload])
        ]);
        $importResponse = curl_exec($ch);
        curl_close($ch);

        // =========================
        // 5. Enviar mensagem (email real)
        // =========================
        $urlMessages = "$baseUrl/accounts/".ID_CONTA."/messages";
        $htmlBody = '
        <html>
            <head>
            <style>
              @media screen and (max-width: 575px) {
                table {
                  display: table !important;
                  padding: 0 !important;
                }
                td {
                  display: block !important;
                  clear: both !important;
                  width: 100% !important;
                  height: auto !important;
                }
                div[data-gjs-type="text"] {
                  padding: 10px 0;
                }
              }
            </style>
            </head>
            <body style="box-sizing: border-box; margin: 0;">
              <table width="100%" style="margin: auto; max-width: 600px; border-collapse: collapse;">
                <tr>
                  <td align="center" style="padding: 0; margin: 0;">
                    <img src="https://assets.mktnaweb.com/accounts/2025/10/29/201007/pictures/2/original_logo-planos.png?1762178235" alt="Memprega" style="display: block; max-width: 100%; height: auto;">
                    <p style="font-family: Arial, Helvetica, sans-serif; font-size: 22px; margin: 10px 0;">
                      ' . htmlspecialchars($variaveisGlobais["Titulo"]) . '
                    </p>
                    <div style="font-family: Arial, Helvetica, sans-serif; font-size: 14px; text-align: left;">
                      <p>' . nl2br($variaveisGlobais["Mensagem"]) . '</p>
                    </div>
                    <hr style="border: none; border-top: 1px solid #ececec; margin: 20px 0;">
                    <p style="font-family: Arial, Helvetica, sans-serif; font-size: 14px; text-align: left;">
                      📲 <strong>Baixe agora o nosso app!</strong><br>
                      Tenha acesso a todos os recursos diretamente do seu celular.<br><br>
                      ➡️ <a href="https://play.google.com/store/apps/details?id=br.com.ocdmkt.Memprega" target="_blank">Google Play</a><br>
                      ➡️ <a href="https://apps.apple.com/br/app/memprega-candidato/id6479995281" target="_blank">App Store</a>
                    </p>
                    <p style="font-family: Arial, Helvetica, sans-serif; font-size: 14px; text-align: left;">
                      Atenciosamente,<br>
                      <strong>Equipe Memprega</strong><br>
                      📞 (11) 94050-6265<br>
                      📱 <a href="http://wa.me/5511940506265" target="_blank">WhatsApp</a><br>
                      🌐 <a href="http://memprega.com.br" target="_blank">www.memprega.com.br</a>
                    </p>
                    <table width="100%" style="margin-top: 20px; background-color: #ececec; text-align: center; border-collapse: collapse;">
					  <tr>
						<!-- Bloco esquerdo vazio -->
						<td width="33.33%" style="background-color: #ececec;">&nbsp;</td>

						<!-- Bloco do meio com as redes sociais -->
						<td width="33.33%" align="center" style="background-color: #ececec; padding: 20px 0;">
						  <a href="http://wa.me/5511940506265" style="margin: 0 5px; display: inline-block;">
							<img src="http://assets.mktnaweb.com/heisenberg/img-whatsapp-gray.png" alt="WhatsApp" style="width: 36px; height: 36px;">
						  </a>
						  <a href="https://www.facebook.com/memprega" style="margin: 0 5px; display: inline-block;">
							<img src="http://assets.mktnaweb.com/heisenberg/img-facebook-gray.png" alt="Facebook" style="width: 36px; height: 36px;">
						  </a>
						  <a href="https://www.instagram.com/memprega.app/" style="margin: 0 5px; display: inline-block;">
							<img src="http://assets.mktnaweb.com/heisenberg/img-instagram-gray.png" alt="Instagram" style="width: 36px; height: 36px;">
						  </a>
						  <a href="https://www.linkedin.com/company/69496480/" style="margin: 0 5px; display: inline-block;">
							<img src="http://assets.mktnaweb.com/heisenberg/img-linkedin-gray.png" alt="LinkedIn" style="width: 36px; height: 36px;">
						  </a>
						</td>

						<!-- Bloco direito vazio -->
						<td width="33.33%" style="background-color: #ececec;">&nbsp;</td>
					  </tr>
					</table>
                  </td>
                </tr>
              </table>
            </body>
        </html>';

        $textBody = strip_tags($variaveisGlobais['Mensagem']);

        $messageData = [
            "message" => [
                "domain_id" => DOMAIN_ID,
                //"template_id" => TEMPLATE_ID,
                "html_body" => $htmlBody,
                "text_body" => $textBody,
                "list_ids" => [$listId],
                "name" => "Envio Automático - " . date('d/m/Y H:i:s'),
                "sender_name" => "Memprega",
                "sender" => "contato@mia.memprega.com.br",
                "subject" => $assunto,
                "scheduled_to" => "now",
                // "variables" => [
                //     "Titulo" => $variaveisGlobais['Titulo'],
                //     "Mensagem" => $variaveisGlobais['Mensagem']
                // ]
            ]
        ];

        $ch = curl_init($urlMessages);
        curl_setopt_array($ch, [
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($messageData)
        ]);
        $sendResponse = curl_exec($ch);
        curl_close($ch);
        
        //file_put_contents("LOCAWEB_RETURN.TXT","send_result = ".print_r(json_decode($sendResponse, true),true).PHP_EOL, FILE_APPEND);
        
        return ['type' => 'OK', 'message' => 'E-mails enviados com sucesso'];
    }
    
    // =======================================
    // Função privada para limpar contatos da lista
    // =======================================
    private function limparContatosLista($listId, $headers, $baseUrl) {
        $urlContacts = "$baseUrl/accounts/".ID_CONTA."/lists/$listId/contacts";
        $continuar = true;

        while ($continuar) {
            $ch = curl_init($urlContacts);
            curl_setopt_array($ch, [
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_RETURNTRANSFER => true
            ]);
            $response = curl_exec($ch);
            curl_close($ch);

            $data = json_decode($response, true);
            if (empty($data['items'])) {
                $continuar = false;
                break;
            }

            foreach ($data['items'] as $contato) {
                if (!empty($contato['id'])) {
                    $urlDelete = "$baseUrl/accounts/".ID_CONTA."/lists/$listId/contacts/{$contato['id']}";
                    $ch = curl_init($urlDelete);
                    curl_setopt_array($ch, [
                        CURLOPT_HTTPHEADER => $headers,
                        CURLOPT_CUSTOMREQUEST => "DELETE",
                        CURLOPT_RETURNTRANSFER => true
                    ]);
                    curl_exec($ch);
                    curl_close($ch);
                }
            }
        }
    }

}

?>