<?php

namespace App\Http\Controllers;

use App\Imports\UsersImport;
use App\Models\Message;
use App\Models\Payment;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class CommonController extends Controller
{
    //
    public function mpesa_callback()
    {
        try {
            header("Content-Type:application/json");
            $resp = '{"ResultCode":0,"ResultDesc":"Confirmation received successfully"}';

            $data = file_get_contents("php://input");
            $data = json_decode($data, true);

            //$sess = $this->input->get('sess');

            //log file
            $filePath = dirname(__DIR__) . "/mpesa_logs/messages.log";
            //error log
            $errorLog = dirname(__DIR__) . "/mpesa_logs/errors.log";

            $Item = $data['Body']['stkCallback']['CallbackMetadata']['Item'];

            $metadata = array(
                'MerchantRequestID' => $data['Body']['stkCallback']['MerchantRequestID'],
                'CheckoutRequestID' => $data['Body']['stkCallback']['CheckoutRequestID'],
                'ResultCode' => $data['Body']['stkCallback']['ResultCode'],
                'ResultDesc' => $data['Body']['stkCallback']['ResultDesc'],
            );

            $mpesaData = array_column($Item, 'Value', 'Name');
            $mpesaData = array_merge($metadata, $mpesaData);

            $jdata = json_encode($mpesaData);

            // perform business logic here

            $jsonData = [
                'receipt_number' => $mpesaData['MpesaReceiptNumber'],
                'amount' => $mpesaData['Amount'],
                // 'TransactionDate' => $mpesaData['TransactionDate'],
                'phone' => $mpesaData['PhoneNumber'],
                'type' => 'hostpot'

            ];

            $pdata = json_encode($jsonData);

            $pc = new Payment;
            $pd = $pc->create($jsonData);

            //open text file for logging messages by appending
            $file = fopen($filePath, "a");
            //log incoming request

            fwrite($file, "\r\n\r\n\r\n\r\n*****Incoming Request From Mpesa Callback*****\r\n\r\n");
            $logEntry = $jdata . PHP_EOL;
            // $logEntry = json_encode($pays) . PHP_EOL;
            fwrite($file, $logEntry);
            // fwrite($file, print_r($mpesaData, true));
            fwrite($file, "\r\n\r\n\r\n\r\n");
            //log response and close file
            fwrite($file, $resp);
            fclose($file);


        } catch (Exception $ex) {
            //append exception to errorLog
            $logErr = fopen($errorLog, "a");
            fwrite($logErr, $ex->getMessage());
            fwrite($logErr, "\r\n");
            fclose($logErr);
        }
        //echo response
        echo $resp;


    }

    public function getMonthTotals(){
        $currentYear = now()->year;
        $firstMonth = Carbon::create($currentYear, 1, 1, 0, 0, 0);
        $lastMonth = Carbon::create($currentYear, 12, 1, 0, 0, 0);


        $months = [];

        // Iterate over each month of the year
        for ($month = 1; $month <= 12; $month++) {
            $firstDayOfMonth = Carbon::createFromDate($currentYear, $month, 1);
            $lastDayOfMonth = $firstDayOfMonth->copy()->endOfMonth();

            $totalAmount = Subscription::whereBetween('created_at', [$firstDayOfMonth, $lastDayOfMonth])
                ->sum('amount');

            // Store the total amount in the array with the month name
            $months[$firstDayOfMonth->format('F')] = $totalAmount;
        }

        //dd($months);

//        $result = [];
//
//        for ($month = 1; $month <= 12; $month++) {
//            $monthName = Carbon::create($currentYear, $month, 1, 0, 0, 0)->format('F');
//            $found = $data->where('month', $currentYear . '-' . str_pad($month, 2, '0', STR_PAD_LEFT))->first();
//
//            $month_res[] = [
//                'month' => $monthName
//            ];
//            $total_amount[] = [
//                'total' => $found ? $found->total_amount : 0,
//            ];
//
////            $result[] = [
////                'month' => $monthName,
////                'total_amount' => $found ? $found->total_amount : 0,
////            ];
//        }
//
//        $months = collect($month_res)->pluck('month')->map(function ($month) {
//            return strtolower($month);
//        })->toArray();
//
//        $total_data = collect($total_amount)->pluck('total')->map(function ($month) {
//            return strtolower($month);
//        })->toArray();

       // dd($months);

        $resData = [
            "months" => $months,
         //   "totals" => $total_data,
            "year" => $currentYear
        ];

        $months = [
            'months' => $months
        ];



        $data = json_decode(json_encode($months), true);

// Get keys (month names)
        $monthNames = array_keys($data['months']);
        $monthValues = array_values($data['months']);

        $data = [
            'months' => $monthNames,
            'totals' => $monthValues
        ];
        return $data;


    }


    public function chartTest()
    {
        return view('dashboard.test');
    }

    public function getTrafficData()
    {
        $client = new RouterOS\Client([
            'host' => 'your_router_ip',
            'user' => 'api_username',
            'pass' => 'api_password',
        ]);

        $request = new RouterOS\Request('/interface/monitor-traffic');

        // You can add additional parameters to the request, e.g., interface name.
        // $request->setArgument('.id', 'interface_id');

        $response = $client->sendSync($request);

        // Process the response (traffic data)
        $trafficData = [];

        foreach ($response as $item) {
            $trafficData[] = [
                'interface' => $item->getProperty('interface'),
                'rx' => $item->getProperty('rx'),
                'tx' => $item->getProperty('tx'),
            ];
        }

        return response()->json($trafficData);
    }

    public function importUsers()
    {
        Excel::import(new UsersImport, 'users.xlsx');

        return redirect('/')->with('success', 'All good!');
    }


    public function testSms()
    {
        $sm = new Message;
        $send = $sm->sendSmsTest('0741931014','Swiftnet Test Sms please ignore it');
        if($send){
            dd('sent');

        }else{
            dd('failed');
        }
    }





}
