<?php

include_once __dir__ . '/../vendor/autoload.php';
use Smalot\PdfParser\Parser;
use Dompdf\Dompdf;

trait PaymentHelper {

    function addCancellationProtocol($company_id) {

        $protocol_number = str_pad(mt_rand(0, 9999999999), 10, '0', STR_PAD_LEFT);
        $sql = "INSERT INTO cancellation_protocol (company, protocol_number) VALUES(:company_id, :protocol_number)"; 
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':company_id' => $company_id,
            ':protocol_number' => $protocol_number
        ]);
        
        return true;

    }

    function getLastCancellationProtocol($company_id) {

        $sql = "SELECT A1.*, A2.companyname FROM cancellation_protocol AS A1
            LEFT JOIN companies AS A2 ON A2.id = A1.company 
            WHERE A1.company = ? ORDER BY A1.id DESC LIMIT 1"; 
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);
        $protocol = $stmt->fetch(PDO::FETCH_ASSOC);
        $fmt_date = date("d/m/Y H:i", strtotime($protocol['canceled_at']));
        $html = file_get_contents(__dir__ . '/../core/pdf/templates/cancellation_protocol.html');
        $html = str_replace("#{protocolNumber}", $protocol['protocol_number'], $html);
        $html = str_replace("#{cancellationDate}", $fmt_date, $html);
        $html = str_replace("#{businessName}", $protocol['companyname'], $html);

        //gera PDF
        $dompdf = new Dompdf(array('enable_remote' => true));
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream("{$protocol['protocol_number']}_{$protocol['companyname']}.pdf", array("Attachment" => 1));

    }

    function deleteSignature($company_id) {

        
        $sql = "DELETE FROM company_signatures WHERE company_id = ? AND type = 'signature'";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);

    }

    function updateSignature(        
        $company_id = null, 
        $plan_id = null, 
        $plan_payment_id = null, 
        $plan_payment_option_id = null,
        $payment_type = null,
        $reference = null,
        $status = null,
        $status_text = null,
        $signature_id = null,
        $signature_plan_id = null,
        $payment_link = null,
        $type = 'signature',
        $price = null,
        $data_signature = null
    ) {        

        $params = array();
        $columns = array();
        $values = array();
        $set_values = array();

        if($company_id) {
            $columns[] = 'company_id';
            $values[] = ':company_id';
            $set_values[] = 'company_id = :company_id';
            $params[':company_id'] = $company_id;
        }

        if($plan_id) {
            $columns[] = 'plan_id';
            $values[] = ':plan_id';
            $set_values[] = 'plan_id = :plan_id';
            $params[':plan_id'] = $plan_id;
        }

        if($plan_payment_id) {
            $columns[] = 'plan_payment_id';
            $values[] = ':plan_payment_id';
            $set_values[] = 'plan_payment_id = :plan_payment_id';
            $params[':plan_payment_id'] = $plan_payment_id;
        }

        if($plan_payment_option_id) {
            $columns[] = 'plan_payment_option_id';
            $values[] = ':plan_payment_option_id';
            $set_values[] = 'plan_payment_option_id = :plan_payment_option_id';
            $params[':plan_payment_option_id'] = $plan_payment_option_id;
        }

        if($payment_type) {
            $columns[] = 'payment_type';
            $values[] = ':payment_type';
            $set_values[] = 'payment_type = :payment_type';
            $params[':payment_type'] = $payment_type;
        }

        if($reference) {
            $columns[] = 'reference';
            $values[] = ':reference';
            $set_values[] = 'reference = :reference';
            $params[':reference'] = $reference;
        }

        if($status) {
            $columns[] = 'status';
            $values[] = ':status';
            $set_values[] = 'status = :status';
            $params[':status'] = $status;
        }

        if($status_text) {
            $columns[] = 'status_text';
            $values[] = ':status_text';
            $set_values[] = 'status_text = :status_text';
            $params[':status_text'] = $status_text;
        }

        if($signature_id) {
            $columns[] = 'signature_id';
            $values[] = ':signature_id';            
            $params[':signature_id'] = $signature_id;
        }

        if($signature_plan_id) {
            $columns[] = 'signature_plan_id';
            $values[] = ':signature_plan_id';
            $set_values[] = 'signature_plan_id = :signature_plan_id';
            $params[':signature_plan_id'] = $signature_plan_id;
        }

        if($payment_link) {
            $columns[] = 'payment_link';
            $values[] = ':payment_link';
            $set_values[] = 'payment_link = :payment_link';
            $params[':payment_link'] = $payment_link;
        }

        if($type) {
            $columns[] = 'type';
            $values[] = ':type';
            $set_values[] = 'type = :type';
            $params[':type'] = $type;
        }

        if($price) {
            $columns[] = 'price';
            $values[] = ':price';
            $set_values[] = 'price = :price';
            $params[':price'] = $price;
        }

        if($data_signature) {
            $columns[] = 'data_signature';
            $values[] = ':data_signature';
            $set_values[] = 'data_signature = :data_signature';
            $params[':data_signature'] = json_encode($data_signature);
        }

        $set_values[] = 'last_update = NOW()';
        $set_values[] = 'signature_date = NOW()';
        $columns = implode(",", $columns);
        $values = implode(",", $values);
        $set_values = implode(",", $set_values);

        $sql = "INSERT INTO company_signatures($columns) VALUES($values) ON DUPLICATE KEY UPDATE
            $set_values";

        $stmt = parent::$conn->prepare($sql);
        $stmt->execute($params);
        
        return true;

    }

    function deleteSignatureQuotes($company_id) {
        $sql = "DELETE FROM signature_quotes WHERE company_id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$company_id]);
    }

    function insertSignatureQuotes($company_id, $plan_id, $plan_payment_id) {

        $sql = "SELECT `period` FROM plan_payment_contracts WHERE id = ?";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$plan_payment_id]);
        $contract = $stmt->fetch(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM plan_options WHERE plan_id = :id AND quota_period = :period";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $plan_id, ':period' => $contract['period']]);
        $options = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $sql = "SELECT * FROM company_signatures WHERE company_id = :company_id AND type = 'signature'";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':company_id' => $company_id]);
        $signature = $stmt->fetch(PDO::FETCH_ASSOC);

        $sql = "INSERT IGNORE INTO signature_quotes (signature_id, company_id, plan_id, plan_option_id, `value`) 
            VALUES(:signature_id, :company_id, :plan_id, :plan_option_id, :value)";
        
        foreach($options as $option) {

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                ':signature_id' => $signature['id'], 
                ':company_id' => $company_id, 
                ':plan_id' => $signature['plan_id'], 
                ':plan_option_id' => $option['id'], 
                ':value' => $option['quota_value']
            ]);

        }

    }

    function updateCampaignProcessList($company_id, $signature_id) {

        $sql = "SELECT CPL.id FROM companies AS C
            LEFT JOIN process_list AS PL ON PL.company = C.id
            LEFT JOIN campaign_process_list AS CPL ON CPL.process_list = PL.id
            WHERE C.id = :company_id
            ORDER BY CPL.date_added DESC LIMIT 1
        ";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':company_id' => $company_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        $campaign_id = $result['id'];
        $sql = "UPDATE campaign_process_list SET signature_id = :signature_id WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':signature_id' => $signature_id, ':id' => $campaign_id]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

    }

    function updateCampaignProcessListStatus($signature_id, $status, $status_text) {
        // Buscar o registro da assinatura
        $sql = "SELECT data_signature FROM company_signatures WHERE signature_id = :id LIMIT 1";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $signature_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            return ['type' => 'ERROR', 'message' => 'Signature não encontrada'];
        }
        // Decodificar JSON
        $data = json_decode($row['data_signature'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return ['type' => 'ERROR', 'message' => 'Erro ao decodificar JSON da assinatura'];
        }
        if (empty($data['process_id']) || empty($data['user_id']) || empty($data['sale_id'])) {
            return ['type' => 'ERROR', 'message' => 'JSON da assinatura está incompleto'];
        }
        // Regra de status
        $rowStatus = ($status === 'ACTIVE') ? 'new' : 'pending';
        // UPSERT
        $sqlUpsert = "
            INSERT INTO campaign_process_list (
                process_list, lead_id, owner_id, payment_type, signature_id, signature_status, signature_status_text, status
            )
            VALUES (
                :process_list, :lead_id, :owner_id, :payment_type, :signature_id, :signature_status, :signature_status_text, :row_status
            )
            ON DUPLICATE KEY UPDATE
                process_list = VALUES(process_list),
                lead_id = VALUES(lead_id),
                owner_id = VALUES(owner_id),
                payment_type = VALUES(payment_type),
                signature_status = VALUES(signature_status),
                signature_status_text = VALUES(signature_status_text),
                status = VALUES(status)
        ";
        $stmtUpsert = parent::$conn->prepare($sqlUpsert);
        $stmtUpsert->execute([
            ':process_list'          => $data['process_id'],
            ':lead_id'               => $data['user_id'],
            ':owner_id'              => $data['sale_id'],
            ':payment_type'          => 'SINGLE_BILLET',
            ':signature_id'          => $signature_id,
            ':signature_status'      => $status,
            ':signature_status_text' => $status_text,
            ':row_status'            => $rowStatus
        ]);
        return ['type' => 'OK'];
    }

}