<?php

namespace App\Helpers;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Str;

class WhatsappHelper
{
    public static function approveExpense($phones, $expense_number, $url = null, $tanggal, $total, $name)
    {
        $client = new Client();

        // Ensure the URL is formatted correctly
        if ($url && !preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }

        // Format the message like the email example using Markdown for WhatsApp
        $message = "
        Halo *{$name}*,
        Pengajuan Expense Anda telah di periksa & disetujui oleh *Admin Region Anda*:
        *Expense Number:* {$expense_number}
        *Expense Date:* " . \Carbon\Carbon::parse($tanggal)->locale('id')->isoFormat('D MMMM Y') . "
        *Total:* Rp " . number_format($total, 0, ',', '.') . "
        Silahkan buka link berikut untuk melihat detail expense Anda: {$url}
        Terima kasih.";

        // Prepare the message for each phone number
        $data = [];
        foreach ($phones as $phone) {
            $data[] = [
                'phone' => $phone,
                'message' => $message,
                'source' => 'web'
            ];
        }

        try {
            // Send the request to the WABLAS API
            $response = $client->post(env('WABLAS_HOST') . '/api/v2/send-message', [
                'headers' => [
                    'Authorization' => env('WABLAS_TOKEN'),
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'data' => $data
                ],
                'verify' => false,
            ]);

            return $response->getBody()->getContents();
        } catch (\Exception $e) {
            AuditTrailHelper::AddAuditTrail('Error', 'Failed to send WhatsApp message at Form (' . $expense_number . ')');
            return null;
        }
    }

    public static function approve2Expense($phones, $expense_number, $url = null, $tanggal, $total, $name)
    {
        $client = new Client();

        // Ensure the URL is formatted correctly
        if ($url && !preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }

        // Format the message like the email example using Markdown for WhatsApp
        $message = "
        Halo *{$name}*,
        Pengajuan Expense Anda telah di periksa & disetujui oleh *Area Manager Anda*:
        *Expense Number:* {$expense_number}
        *Expense Date:* " . \Carbon\Carbon::parse($tanggal)->locale('id')->isoFormat('D MMMM Y') . "
        *Total:* Rp " . number_format($total, 0, ',', '.') . "
        Silahkan buka link berikut untuk melihat detail expense Anda: {$url}
        Terima kasih.";

        // Prepare the message for each phone number
        $data = [];
        foreach ($phones as $phone) {
            $data[] = [
                'phone' => $phone,
                'message' => $message,
                'source' => 'web'
            ];
        }

        try {
            // Send the request to the WABLAS API
            $response = $client->post(env('WABLAS_HOST') . '/api/v2/send-message', [
                'headers' => [
                    'Authorization' => env('WABLAS_TOKEN'),
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'data' => $data
                ],
                'verify' => false,
            ]);

            return $response->getBody()->getContents();
        } catch (\Exception $e) {
            AuditTrailHelper::AddAuditTrail('Error', 'Failed to send WhatsApp message at Form (' . $expense_number . ')');
            return null;
        }
    }

    public static function rejectExpense($phones, $expense_number, $url = null, $tanggal, $total, $name)
    {
        $client = new Client();

        // Ensure the URL is formatted correctly
        if ($url && !preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }

        // Format the message like the email example using Markdown for WhatsApp
        $message = "
        Halo *{$name}*,
        Pengajuan pengeluaran baru dengan detail berikut telah ditolak:
        *Expense Number:* {$expense_number}
        *Expense Date:* " . \Carbon\Carbon::parse($tanggal)->locale('id')->isoFormat('D MMMM Y') . "
        *Total:* Rp " . number_format($total, 0, ',', '.') . "
        Silahkan buka link berikut untuk melihat detail expense Anda: {$url}
        Terima kasih.";

        // Prepare the message for each phone number
        $data = [];
        foreach ($phones as $phone) {
            $data[] = [
                'phone' => $phone,
                'message' => $message,
                'source' => 'web'
            ];
        }

        try {
            // Send the request to the WABLAS API
            $response = $client->post(env('WABLAS_HOST') . '/api/v2/send-message', [
                'headers' => [
                    'Authorization' => env('WABLAS_TOKEN'),
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'data' => $data
                ],
                'verify' => false,
            ]);

            return $response->getBody()->getContents();
        } catch (\Exception $e) {
            AuditTrailHelper::AddAuditTrail('Error', 'Failed to send WhatsApp message at Form (' . $expense_number . ')');
            return null;
        }
    }

    public static function finalApprove($phones, $expense_number, $url = null, $tanggal, $total, $name)
    {
        $client = new Client();

        // Ensure the URL is formatted correctly
        if ($url && !preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }

        // Format the message like the email example using Markdown for WhatsApp
        $message = "
        Halo *{$name}*,
        Pengajuan Expense Anda telah di setujui *( FINAL APPROVE )* oleh *MOM Region / HOSM* anda:
        *Expense Number:* {$expense_number}
        *Expense Date:* " . \Carbon\Carbon::parse($tanggal)->locale('id')->isoFormat('D MMMM Y') . "
        *Total:* Rp " . number_format($total, 0, ',', '.') . "
        Silahkan buka link berikut untuk melihat detail expense Anda: {$url}
        Terima kasih.";

        // Prepare the message for each phone number
        $data = [];
        foreach ($phones as $phone) {
            $data[] = [
                'phone' => $phone,
                'message' => $message,
                'source' => 'web'
            ];
        }

        try {
            // Send the request to the WABLAS API
            $response = $client->post(env('WABLAS_HOST') . '/api/v2/send-message', [
                'headers' => [
                    'Authorization' => env('WABLAS_TOKEN'),
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'data' => $data
                ],
                'verify' => false,
            ]);

            return $response->getBody()->getContents();
        } catch (\Exception $e) {
            AuditTrailHelper::AddAuditTrail('Error', 'Failed to send WhatsApp message at Form (' . $expense_number . ')');
            return null;
        }
    }

    public static function newExpense($phones, $expense_number, $url = null, $tanggal, $total, $name)
    {
        $client = new Client();

        // Ensure the URL is formatted correctly
        if ($url && !preg_match('/^https?:\/\//', $url)) {
            $url = 'https://' . $url;
        }

        // Format the message like the email example using Markdown for WhatsApp
        $message = "
        Halo *{$name}*,
        Pengajuan pengeluaran baru dengan detail berikut telah dibuat:
        *Expense Number:* {$expense_number}
        *Expense Date:* " . \Carbon\Carbon::parse($tanggal)->locale('id')->isoFormat('D MMMM Y') . "
        *Total:* Rp " . number_format($total, 0, ',', '.') . "
        Silahkan buka link berikut untuk melihat detail expense Anda: {$url}
        Terima kasih.";

        // Prepare the message for each phone number
        $data = [];
        foreach ($phones as $phone) {
            $data[] = [
                'phone' => $phone,
                'message' => $message,
                'source' => 'web'
            ];
        }

        try {
            // Send the request to the WABLAS API
            $response = $client->post(env('WABLAS_HOST') . '/api/v2/send-message', [
                'headers' => [
                    'Authorization' => env('WABLAS_TOKEN'),
                    'Content-Type' => 'application/json'
                ],
                'json' => [
                    'data' => $data
                ],
                'verify' => false,
            ]);

            return $response->getBody()->getContents();
        } catch (\Exception $e) {
            AuditTrailHelper::AddAuditTrail('Error', 'Failed to send WhatsApp message at Form (' . $expense_number . ')');
            dd($e);
            return null;
        }
    }
}