<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use App\Utilities\ApiCalls;
use Session;
use Illuminate\Pagination\LengthAwarePaginator;
use GuzzleHttp\Client;
use DateTime;

class ClientsTrafficController extends Controller
{
    public function indexNew(){
        $search = $request->input('search');
        $client_id = session('current_user.org_id');
        $clients_url = "messages/client/$client_id?page=0&size=20&sort=createdAt,desc";
        $result = ApiCalls::CurlGet($clients_url);
        $result_arr = json_decode($result);

        $items = collect($result_arr->content); // Convert API array to Collection

        if ($search) {
            $items = $items->filter(function ($item) use ($search) {
                return stripos($item['name'], $search) !== false;
            });
        }
        $currentPage = Paginator::resolveCurrentPage() ?: 1;
        $perPage = $result_arr->size;
        $currentPageItems = $items->slice(($currentPage - 1) * $perPage, $perPage)->all();

        $paginatedItems = new LengthAwarePaginator(
            $currentPageItems, 
            $items->count(), 
            $perPage, 
            $currentPage, 
            ['path' => $request->url(), 'query' => $request->query()]
        );
    }
    public function indexTest(){
        $data = ['page_title' => 'Test Page'];
        return view('client-traffic.test', $data);
    }
    public function index(){
        
        $client_id = session('current_user.org_id');
        $ucm_org_id = session('current_user.ucm_org_id');
        // dd($client_id);
        $clients_url = "messages/client/$client_id?page=0&size=1000&sort=createdAt,desc";
        $result = ApiCalls::CurlGet($clients_url);
        $result_arr = json_decode($result);
        // dd($result_arr);

        $current_date = new DateTime();
        
        $start_date = $current_date->modify('-10 days');
        $start_date = $start_date->format('Y-m-d');
        $end_date = date('Y-m-d');
        $daily_smsunits_url = "ucm/reports/daily-sms-units?from=$start_date&to=$end_date&ucm_org_id=$ucm_org_id";
        
        $result = ApiCalls::CurlGet($daily_smsunits_url);
        $sms_units_arr = json_decode($result, true);
        

        $daily_smsunits_url_split = "ucm/reports/daily-sms-units-by-network?from=$start_date&to=$end_date&ucm_org_id=$ucm_org_id";
        // dump($daily_smsunits_url_split);
        $result = ApiCalls::CurlGet($daily_smsunits_url_split);
        $split_sms_units_arr = json_decode($result, true);
        // dd($split_sms_units_arr);
        $orgId = session('current_user.org_id');
        $sms_balance_url = "clients/$orgId/balance";
        $result = ApiCalls::CurlGet($sms_balance_url);
        
        $balance_arr = json_decode($result, true);
        /*
            array:4 [▼ // app/Http/Controllers/ClientsTrafficController.php:67
              "reportDate" => "2026-05-10 to 2026-05-20"
              "orgId" => 629
              "Airtel SMSUnits" => 401095
              "TNM SMSUnits" => 18796
            ]

            "reportDate" => "2026-05-10 to 2026-05-20"
            "orgId" => 629
            "Airtel SMSUnits" => 401095
            "TNM SMSUnits" => 18796
        */
        // dump($split_sms_units_arr);
        
        if ($ucm_org_id == 629) {
            $airtel_rate = 14;
            $tnm_rate = 18;
            $airtel_computation = $split_sms_units_arr['Airtel SMSUnits'] * $airtel_rate; 
            $tnm_computation = $split_sms_units_arr['TNM SMSUnits'] * $tnm_rate;
            $charge_computation = $airtel_computation + $tnm_computation;
            $split_sms_units_arr['charge_computation'] = number_format($charge_computation);

            $data = [
                'page_title' => 'SMS Traffic',
                'traffic_arr' => $result_arr,
                'sms_units_arr' => $sms_units_arr,
                'split_sms_units_arr' => $split_sms_units_arr,
                'charge_computation' => $charge_computation,
                'balance_arr' => $balance_arr
            ];
        }
        elseif($ucm_org_id == 701){
            // "movitelMzSmsUnits" => 0
            // "tmcelMzSmsUnits" => 0
            // "vodacomMzSmsUnits" => 1
            $movitel_rate = 0.32;
            $tmcell_rate = 0.32;
            $vodacom_rate = 0.32;
            $movitel_computation = $split_sms_units_arr['movitelMzSmsUnits'] * $movitel_rate; 
            $tmcell_computation = $split_sms_units_arr['tmcelMzSmsUnits'] * $tmcell_rate;
            $vodacom_computation = $split_sms_units_arr['tmcelMzSmsUnits'] * $vodacom_rate;

            $charge_computation = $movitel_computation + $tmcell_computation + $vodacom_computation;
            $split_sms_units_arr['charge_computation'] = number_format($charge_computation);
            $split_sms_units_arr['units_computation'] = $split_sms_units_arr['movitelMzSmsUnits'] + $split_sms_units_arr['tmcelMzSmsUnits'] + $split_sms_units_arr['vodacomMzSmsUnits'];
            $data = [
                'page_title' => 'SMS Traffic',
                'traffic_arr' => $result_arr,
                'sms_units_arr' => $sms_units_arr,
                'split_sms_units_arr' => $split_sms_units_arr,
                'charge_computation' => $charge_computation,
                'balance_arr' => $balance_arr
            ];
        }
        
        
        // dd($data); 
        return view('client-traffic.index-main', $data);
    }

    public function indexTabulator(Request $request){
        $client = new Client();
    
        $page = $request->input('page', 0); // Note: This API seems 0-indexed
        $size = $request->input('size', 20);
        /*
        $response = $client->request('GET', 'http://62.171.149.214:9990/api/messages/client/1?page=0&size=20&sort=createdAt,desc', [
            'query' => [
                'page' => $page,
                'size' => $size,
            ],
            'headers' => [
                'Accept'        => 'application/json',
            ]
        ]);

        $data = json_decode($response->getBody(), true);

        */
        $client_id = session('current_user.org_id');
        $clients_url = "messages/client/$client_id?page=0&size=20&sort=createdAt,desc";
        $result = ApiCalls::CurlGet($clients_url);
        // $content_only =  collect($result['content'])->toArray();
        $data = json_decode($result, true);

        // dd($data['content']);

        return response()->json($data);
        // return response()->json([
        //     'last_page' => $data['totalPages'],
        //     'data'      => $data['content'],
        //     'total'     => $data['totalElements']
        // ]);
    }
    public function getClientApps(){
        $client_id = session('current_user.org_id');

        $apps_url = "applications/client/$client_id?page=0&size=20&sort=createdAt,desc";
        $result = ApiCalls::CurlGet($apps_url);
        $result_arr = json_decode($result);
        $data = [
            'page_title' => 'Applications',
            'apps_arr' => $result_arr
        ];
        return view('client-traffic.client-apps', $data);
    }


    public function smsForm(){
        //check if client has an app 

        $data = [
            'page_title' => 'Send SMS',
        ];
        return view('client-traffic.send-sms', $data);

    }
    public function store(Request $request){
        //233244982690,233553175995,233204040805
        $this->validate($request, [
            'message' => 'required',
            'sender_id' => 'required|max:11',
            'recipients_file'=> 'mimes:csv,txt|max:4096',
            'pasted' => 'sometimes',
        ]);
        $recipients_arr = [];        
        
        if ($request->filled('pasted')) {
            $pasted_arr = explode(",", $request->pasted); 
            foreach ($pasted_arr as $value) {
                if (ctype_digit($value) && (strlen($value) == 11 || strlen($value) == 12)) {
                    $recipients_arr[] = trim($value);
                }
                else{
                    continue;
                }
                
            }
        }
        if ($request->hasFile('recipients_file')) {
            $file = fopen($request->file('recipients_file'), 'r');
            $data = fgetcsv($file, 1000, ',');
            foreach ($data as $value) {
                $recipients_arr[] = trim($value);
            }
            fclose($file);
        }
        $recipients_arr = array_unique($recipients_arr);
        
        $client_id = session('current_user.org_id');

        foreach ($recipients_arr as $phone) {
            $payload = [
                'from' => $request->sender_id, 
                'to' => $phone,
                'refId' => uniqid('cmlportal_'),
                'message' => $request->message
            ];
            \Log::info('Payload details ' . json_encode($payload));
            $send_sms_url = "sms/send";
            $result = ApiCalls::CurlPost(json_encode($payload), $send_sms_url);
            \Log::info('Message Successfully submitted ' . $result);
        }        
        Session::flash('success_message', 'Message successfully submitted for delivery!');
        return redirect("send-sms");
    }
    public function dailySmsUnits(Request $request){
        $this->validate($request, [
            'start_date' => 'required|date',
            'end_date' => 'required|date',
        ]);
        $start_date = $request->start_date;
        $end_date = $request->end_date;
        $client_id = session('current_user.org_id');
        $ucm_org_id = session('current_user.ucm_org_id');
        /*
        $daily_smsunits_url = "ucm/reports/daily-sms-units?from=$start_date&to=$end_date";
        $result = ApiCalls::CurlGet($daily_smsunits_url);
        \Log::info('SMS Units Response ' . $result);
        */

        $daily_smsunits_url_split = "ucm/reports/daily-sms-units-by-network?from=$start_date&to=$end_date&ucm_org_id=$ucm_org_id";
        $result = ApiCalls::CurlGet($daily_smsunits_url_split);
        $split_sms_units_arr = json_decode($result, true);
        \Log::info('SMS Units Response ' . $result);

        $data = json_decode($result, true);

        if ($ucm_org_id == 629) {

            $airtel_rate = 14;
            $tnm_rate = 18;
            
            $airtel_computation = $split_sms_units_arr['Airtel SMSUnits'] * $airtel_rate; 
            $tnm_computation = $split_sms_units_arr['TNM SMSUnits'] * $tnm_rate;

            $charge_computation = (int)$airtel_computation + (int)$tnm_computation;
            
            $data['ucm_org_id'] = $ucm_org_id;
            $data['charge_computation'] = number_format($charge_computation);
            $data['airtel_sms_units'] = number_format($split_sms_units_arr['Airtel SMSUnits']);
            $data['tnm_sms_units'] = number_format($split_sms_units_arr['TNM SMSUnits']);

            return response()->json($data);
        }
        elseif($ucm_org_id == 701){
            // "movitelMzSmsUnits" => 0
            // "tmcelMzSmsUnits" => 0
            // "vodacomMzSmsUnits" => 1
           
            $movitel_rate = 0.32;
            $tmcell_rate = 0.32;
            $vodacom_rate = 0.32;

            $movitel_computation = $split_sms_units_arr['movitelMzSmsUnits'] * $movitel_rate; 
            $tmcell_computation = $split_sms_units_arr['tmcelMzSmsUnits'] * $tmcell_rate;
            $vodacom_computation = $split_sms_units_arr['tmcelMzSmsUnits'] * $vodacom_rate;

            
            $charge_computation = (int)$movitel_computation + (int)$tmcell_computation + (int)$vodacom_computation;
    
            $data['ucm_org_id'] = $ucm_org_id;
            $data['charge_computation'] = number_format($charge_computation);
            $units_computation = (int)$split_sms_units_arr['movitelMzSmsUnits'] + (int)$split_sms_units_arr['tmcelMzSmsUnits'] + (int)$split_sms_units_arr['vodacomMzSmsUnits'];
            $data['units_computation'] = $units_computation;
            return response()->json($data);
        }
        /*
        $airtel_rate = 14;
        $tnm_rate = 18;
        
        $airtel_computation = $split_sms_units_arr['Airtel SMSUnits'] * $airtel_rate; 
        $tnm_computation = $split_sms_units_arr['TNM SMSUnits'] * $tnm_rate;
        $charge_computation = (int)$airtel_computation + (int)$tnm_computation;
        // dump($airtel_computation);
        // dump($tnm_computation);
        // dd($charge_computation);

        // $charge_computation = ($split_sms_units_arr['Airtel SMSUnits'] * $airtel_rate) + ($split_sms_units_arr['TNM SMSUnits'] + $tnm_rate);
        $data['charge_computation'] = number_format($charge_computation);
        $data['airtel_sms_units'] = number_format($split_sms_units_arr['Airtel SMSUnits']);
        $data['tnm_sms_units'] = number_format($split_sms_units_arr['TNM SMSUnits']);
        */

        
    }
    public function dailySmsUnitsSplit(){

        $clients_url = "ucm/reports/daily-sms-units-by-network?from={{reportDateFrom}}&to={{reportDateTo}}";
    }
    public function newAppStore(Request $request){

        $this->validate($request, [
            'application_name' => 'required',
            'orgId' => 'required',
            'application_type'=> 'required',            
        ]);
        $payload['name'] = $request->application_name;
        $payload['type'] = $request->application_type;
        $payload['orgId'] = $request->orgId;
      
        $create_application_url = "applications";
        $result = ApiCalls::CurlPost(json_encode($payload), $create_application_url);
        \Log::info('Application creation request ' . json_encode($payload));
        \Log::info('Application Successfully created ' . $result);
        $result_arr = json_decode($result, true);
        //save application in a db
        
        $retval = Models\ClientApplication::create($result_arr);
        return response()->json(json_decode($result, true));
    }
}
