<?php

namespace App\Services;

use App\Services\WhatsApp;
use App\Models\WhatsappConfig;
use App\Models\WhatsappLogs;
use App\Models\WhatsappStoreCredits;

class SendWhatsAppService
{
    public static function templateCategory(?string $identifier): string
    {
        if (!$identifier) {
            return 'marketing';
        }

        $utilityTemplates = config('whatsapp.utility_templates', []);
        return in_array($identifier, $utilityTemplates, true) ? 'utility' : 'marketing';
    }

    public static function creditsForTemplate(?string $identifier): int
    {
        $category = self::templateCategory($identifier);
        return (int) config('whatsapp.credit_costs.' . $category, $category === 'utility' ? 1 : 4);
    }

    public function sendWhatsApp($to, $from, $data , $order)
    {
        $WhatsAppConfig = WhatsappConfig::where('id' , '1')->where('is_active' , 1)->first();
         
        if ($WhatsAppConfig) {
           
            $WhatsappStoreCredits = WhatsappStoreCredits::firstOrNew(['id' => 1]);
            $totalUsedCredits = (int) ($WhatsappStoreCredits->used_credits ?? 0);
            $limitCredits = (int) ($WhatsappStoreCredits->total_credits ?? 0);
            $templateIdentifier = $data['whatsapp_template'] ?? null;
            $requiredCredits = self::creditsForTemplate($templateIdentifier);
            $availableCredits = max(0, $limitCredits - $totalUsedCredits);
              
              
            $otp_class = __NAMESPACE__ . '\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', 'WhatsApp')));
                  
            if (class_exists($otp_class) && $availableCredits >= $requiredCredits) {
                $response =  (new $otp_class)->send($to, $from, $data , $order);
                $status = 0;
              
                if(isset($response)){
                    if(isset(json_decode($response)->result) && json_decode($response)->result == 'success'){
                        $status = 1;
                        if($WhatsappStoreCredits){
                            $WhatsappStoreCredits->used_credits = $totalUsedCredits + $requiredCredits;
                            $WhatsappStoreCredits->save();
                        }
                    }
                }
                
                $log = new WhatsappLogs();

                $log->identifier     = $data['whatsapp_template'] ?? null;
                $log->sender_name     = $data['sender_name'];
                $log->customer_id    = $order->user_id ?? null;
                $log->order_code     = '#'.$order->id ?? null;
                $log->whatsapp_body  = json_encode($data);
                $log->phone          = $to;
                $log->status         =  $status;
                $log->response       =  $response;

                $log->save();
            
                return  $response;
            }

            if ($availableCredits < $requiredCredits) {
                $response = json_encode([
                    'result' => 'failed',
                    'message' => 'Insufficient WhatsApp credits',
                    'required_credits' => $requiredCredits,
                    'available_credits' => $availableCredits,
                    'template_identifier' => $templateIdentifier,
                ]);

                $log = new WhatsappLogs();
                $log->identifier = $data['whatsapp_template'] ?? null;
                $log->sender_name = $data['sender_name'] ?? ($from ?? '');
                $log->customer_id = $order->user_id ?? 0;
                $log->order_code = '#' . ($order->id ?? '');
                $log->whatsapp_body = json_encode($data);
                $log->phone = $to;
                $log->status = 0;
                $log->response = $response;
                $log->save();

                return $response;
            }
        }
        return;
    }
}
