<?php

namespace App\Http\Controllers;

use App\Models\WhatsAppBotDevice;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class WhatsAppBotDeviceController extends Controller
{
    private $prefix = "admin/whatsapp-bot/";
    private $resources = [];
    private $checkPermissionAndRolesController;

    function __construct(
        CheckPermissionsAndRolesController $checkPermissionAndRolesController
    ) {
        $this->resources['prefix'] = $this->prefix;
        $this->checkPermissionAndRolesController = $checkPermissionAndRolesController;
    }
    public function index(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $this->resources['data'] = $this->get($request);
        return view('admin.whatsapp-robot.wsr_add')->with($this->resources);
    }
    public function orderindex(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $this->resources['data'] = $this->get($request);
        return view('admin.whatsapp-sender.order.orders_manage')->with($this->resources);
    }
    public function store(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $credentials = $request->validate([
            'name' => ['required'],
            'number' => ['required']
        ]);
        try {
            $this->resources['data'] = $this->get($request);
            $session_id = $this->generateSessionId(20);
            $result = $this->create_session($session_id);
            if ($result) {
                $requestParam = $request->all();
                $requestParam['created_by'] = Auth::user()->id;
                $requestParam['status'] = 'initiate';
                $requestParam['session_id'] = $session_id;
                $requestParam['qr_update_time'] = now();
                WhatsAppBotDevice::create($requestParam);
                $this->resources['messages'] = array("type" => "success", "description" => "Device creation success");
                return redirect()->back()->with('messages', $this->resources);
            } else {
                $this->resources['messages'] = array("type" => "success", "description" => "Device session creation success");
                return redirect()->back()->with('messages', $this->resources);
            }
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function get($request)
    {
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            if (!$superAdmin) {
                $result = WhatsAppBotDevice::where('created_by', Auth::user()->id)->paginate(15);
            } else {
                $result = WhatsAppBotDevice::paginate(15);
            }
            return $result;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function create_session($session_id = null)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/create-session?session_id=' . $session_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return array("response" => $response);
        } else {
            return false;
        }
    }
    public function get_qr($session_id)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/get-qr?session_id=' . $session_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return json_decode($response, true);
        } else {
            return false;
        }
    }
    public function check_session($session_id)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/check-status?session_id=' . $session_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return json_decode($response, true);
        }
        return false;
    }
    public function send_message($chatID, $session_id, $message)
    {

        $curl = curl_init();
        $message = urlencode($message);
        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/send-message?chatID=' . $chatID . '&session_id=' . $session_id . '&message=' . $message,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return $response;
        } else {
            return false;
        }
    }
    public function delete_session($session_id)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/disconnect?session_id=' . $session_id,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return json_decode($response, true);
        }
        return false;
    }
    /**
     * @return unique id
     */
    public function generateSessionId($length = 10)
    {
        try {
            $id =  substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
            return strtoupper($id);
        } catch (\Throwable $th) {
            throw $th;
        }
    }
    public function edit(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $this->resources['data'] = $this->getById($request);
        return view('admin.whatsapp-robot.wsr_edit')->with($this->resources);
    }

    public function getById($request)
    {
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $query = WhatsAppBotDevice::where('id', $request->id);
            if (!$superAdmin) {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->first();
            return $result;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function update(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $credentials = $request->validate([
            'id' => ['required'],
            'name' => ['required'],
            'number' => ['required'],
        ]);
        try {

            $requestParam = $request->all();
            WhatsAppBotDevice::where('id', $requestParam['id'])->update([
                'name' => $requestParam['name'],
                'number' => $requestParam['number'],
                'description' => $requestParam['description'],

            ]);
            $this->resources['messages'] = array("type" => "success", "description" => "Device updated success");
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function delete(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $request->validate([
            'id' => ['required'],
        ]);
        try {
            $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            $data = $this->getById($request);
            $session_id = $data['session_id'];
            $result = $this->delete_session($session_id);
            $query = WhatsAppBotDevice::where('id', $request->id);
            if (!$superAdmin) {
                $query->where('created_by', $request->user()->id);
            }
            $result = $query->delete();

            if ($result) {
                $this->resources['messages'] = array("type" => "success", "description" => "WhatsApp Bot Device deleted success");
            } else {
                $this->resources['messages'] = array("type" => "error", "description" => "WhatsApp Bot Device deleted failed");
            }
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function scan(Request $request)
    {
        try {
            $id = $request->id;
            $get_data = $this->getData($id);
            $this->get_qr($get_data['session_id']);
            $qr = '';
            if (isset($get_data['data']['qr'])) {
                $qr = $get_data['data']['qr'];
            }
            return response()->json(['qr' => $qr], 200);
        } catch (\Throwable $th) {
            return response()->json($th->getMessage(), 500);
        }
    }

    public function getData($id)
    {
        try {
            return WhatsAppBotDevice::select('data', 'status', 'session_id')->where('id', $id)->first();
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function statusUpdate(Request $request)
    {
        try {
            // $superAdmin = $this->checkPermissionAndRolesController->superAdmin($request);
            // $query = WhatsAppBotDevice::select('data', 'id', 'status');
            // if (!$superAdmin) {
            //     $query->where('created_by', $request->user()->id);
            // }
            // $result = $query->get();
            // if ($result) {
            //     foreach ($result as $value) {
            //         $session_id = $value['data']['request_data']['id'];
            //         $result = $this->check_session($session_id);
            //         if ($result) {
            //             WhatsAppBotDevice::where('id', $value['id'])->update([
            //                 'status' => $result['status']
            //             ]);
            //         } else {
            //             if ($value['status'] == 'connected') {
            //                 WhatsAppBotDevice::where('id', $value['id'])->update([
            //                     'status' => 'disconnected'
            //                 ]);
            //             }
            //         }
            //     }
            // }
            return response()->json("true", 200);
        } catch (\Throwable $th) {
            return response()->json($th->getMessage(), 500);
        }
    }
    public function statusUpdateById(Request $request)
    {
        try {
            $requestAll = $request->all();
            $id = $requestAll['id'];
            $get_data = $this->getData($id);
            $responseData = $get_data['data'];
            return response()->json(['qr' => isset($responseData['qr']) ? $responseData['qr'] : '', 'status' => $get_data['status']], 200);
        } catch (\Throwable $th) {
            return response()->json($th->getMessage() . ' ||| ' . $th->getLine(), 500);
        }
    }
    public function disconnect(Request $request)
    {
        $this->checkPermissionAndRolesController->permissionTo($request, ['permission' => 'WhatsApp Bot']);
        $credentials = $request->validate([
            'id' => ['required'],
        ]);

        try {
            $requestParam = $request->all();
            $data = $this->getById($request);
            if ($data['status'] == 'connected') {
                $session_id = $data['session_id'];
                $result = $this->delete_session($session_id);
                if ($result) {
                    WhatsAppBotDevice::where('id', $requestParam['id'])->update([
                        'status' => $result['status'],
                        'data' => NULL
                    ]);
                    $this->resources['messages'] = array("type" => "success", "description" => "Device disconected success");
                    return redirect()->back()->with('messages', $this->resources);
                }
            }
            $this->resources['messages'] = array("type" => "error", "description" => "Something went wrong!");
            return redirect()->back()->with('messages', $this->resources);
        } catch (\Throwable $th) {
            $this->resources['messages'] = array("type" => "error", "description" => $th->getMessage());
            return redirect()->back()->with('messages', $this->resources);
        }
    }
    public function statusCallback(Request $request)
    {
        try {
            $requestAll = $request->all();
            Log::info("statusCallback", [$requestAll]);
            $session_id = $requestAll['session_id'];
            $status = $requestAll['status'];
            $update = WhatsAppBotDevice::where('session_id', $session_id)->update([
                'status' => $status
            ]);

            return response()->json($update, 200);
        } catch (\Throwable $th) {
            Log::info("statusCallback", [$th->getMessage() . ' ||| ' . $th->getLine()]);
            return response()->json($th->getMessage() . ' ||| ' . $th->getLine(), 500);
        }
    }
    public function qrCallback(Request $request)
    {
        try {
            $requestAll = $request->all();
            Log::info("qrCallback", [$requestAll]);
            $session_id = $requestAll['session_id'];
            $data = $requestAll['data'];
            $update = WhatsAppBotDevice::where('session_id', $session_id)->update([
                'data' => $data,
                'qr_update_time' => now()
            ]);

            return response()->json($update, 200);
        } catch (\Throwable $th) {
            Log::info("qrCallback", [$th->getMessage() . ' ||| ' . $th->getLine()]);
            return response()->json($th->getMessage() . ' ||| ' . $th->getLine(), 500);
        }
    }

    public function ping()
    {
        try {
            $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => env('WHATSAPP_BOT_SESSION_URL') . '/ping',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return response()->json(true, 200);
        } else {
            return response()->json(false, 200);
        }
            
        } catch (\Throwable $th) {
            return response()->json($th->getMessage() . ' ||| ' . $th->getLine(), 500);
        }

        
    }
}
