<?php

namespace App\Http\Controllers\api\v1;

use Log;
use Exception;
use Illuminate\Http\Request;
use App\Services\HotspotService;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;


class HotSpotController extends Controller
{
    /**
     * HotSpot login
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        try {
            // $zone = "gmc sa";
            // $zone = str_replace(' ', '+', $zone);
            // $hotspotService = new HotspotService();

            // $url = 'customer';
            // $customer_login = "0787430901@gmc-sa.com"; //$request->email;
            // $getResponse = $hotspotService->get($url . '?zone_name=' . strtoupper($zone) . '&customer_login=' . $customer_login);

            // if (json_decode($getResponse)->http_status != 200) {
            //     return $this->ReturnResponse(false, "Impossible de connecter ce client au hotspot ", [], 404);
            // }
            $datas = '{
                        "remaining_time": "00:10:00",
                        "total_time": "01:00:00",
                        "is_ads": true
                    }';
            $data = json_decode($datas, true);
            // return $this->ReturnResponse(true, 'Information du hotspot', [json_decode($getResponse)->data]);
            return $this->ReturnResponse(true, 'Information du hotspot',  [$data]);
        } catch (Exception $e) {
            $message = "HotSpotController - Login - " . $e->getMessage() . " - line: " . $e->getLine() . " - file: " . $e->getFile();
            //Logging de l erreur
            //\Log::channel('customlog')->error($message);
            return $this->ReturnResponse(false, $message, [], 500);
        }
    }

    /**
     * HotSpot Payment
     * @param Request $request
     * @return JsonResponse
     */
    public function payment(Request $request): JsonResponse
    {
        try {
            $result = [
                'token'             => "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiMmQ3MGVmYTg2ZjRlZGM1MThkYTdmNGNkM2VlNjRlOGQzNTA0ZGYxNWVlOTgzY2UyYWE1NjhkNzM5YTA4OWViNGZhY2YyYTU0Mjg5OGZhNzMiLCJpYXQiOjE3MDQ5Njc0OTcuMzA3MjM3LCJuYmYiOjE3MDQ5Njc0OTcuMzA3MjQsImV4cCI6MTcwNTA1NzQ5Ny4zMDEwOSwic3ViIjoiNCIsInNjb3BlcyI6W119.Fncv4TLDb_rmIHCJSYx5MAJThUwJ41isRuxVzPkSoZ4myGZX1bq-_jMnGeN2i-HN3DjJGOE_u0x6kta9ta9n5VTvstKKdx1XFw3ztZ2F5ST1jd75hr6c-8b0BFVxrhP-DtkMb3H7_FG8KU0_B4Bd8F2_lgcAiZCDfI1LTsQ0nYr90SVICiyRhe4NZ_ISPESW818bEjii7XoH43elL9fU2xEpvJNsdMPo118gi8pymTPnSOLEUTH6_ieMd8nnC2d8vR86ZXvee1ikEMbdYoxKBsknThGyYpq2gcSbA4MczOYolMrC-e9MUMG6FxlzkVv9GJt4ipvu8qYLps4LSmvPZkNAudJZEKMbHfkYsp2nrqAvX1oM53cjRz0CCCOQJ7KdKEyFjkP1o7OwE7iL_gouVkg0MPBYrRDWAnLFTdyRgdmZOXkYSyaWjjNFm3Anhy4oBPE8oQ5JHOEDIQK0iByX2vukDPU8kYYTvQzkmA8Q87mIXARLgs0cfZCzMYI2havHcHUniwMVptwNszdpe_uA94MkUFpOG42tYDR03Sax00Ilo96n5JQ2_EcOiNhYMqvEL8xFCic0wyZ6k_1RvohHplJ8u76AokgJ9oxMYFSfvB_a3unIwIddy-hhkj7EgQLOPdRC4yaRRNDAknffgzG_RP-dqc1cuIQRiOF6M-VbSys",
                'remaining-time'    => $request->extend
            ];

            return $this->ReturnResponse(true, "Votre compte a bien été rechargé de " . $request->extend . " minutes", $result);
        } catch (Exception $e) {
            $message = "HotSpotController - payment - " . $e->getMessage() . " - line: " . $e->getLine() . " - file: " . $e->getFile();
            //Logging de l erreur
            Log::channel('customlog')->error($message);
            return $this->ReturnResponse(false, $message, [], 500);
        }
    }


    /**
     * HotSpot Remaining Time
     * @param Request $request
     * @return JsonResponse
     */
    public function remainingTime(Request $request): JsonResponse
    {
        try {
            return $this->Login($request);

            /*
            $time 	= rand(0,30);
            $result = ['remaining-time' => $time];
            return $this->ReturnResponse(true, "Il vous reste ". $time . " minutes de connexion", $result);
            */
        } catch (Exception $e) {
            $message = "HotSpotController - remainingTime - " . $e->getMessage() . " - line: " . $e->getLine() . " - file: " . $e->getFile();
            //Logging de l erreur
            Log::channel('customlog')->error($message);
            return $this->ReturnResponse(false, $message, [], 500);
        }
    }

    public function listOfOffers(Request $request)
    {

        $validator = Validator::make(
            $request->all(),
            [
                'zone_name' => 'required',
            ]
        );

        // If Errors
        if ($validator->fails()) {
            return $this->ReturnResponse(false, $validator->errors(), [], 401);
        }
        $zone = str_replace(' ', '+', $request->zone_name);
        // $hotspotService = new HotspotService();

        // $getResponse = $hotspotService->get('subscriptions?zone_name='. strtoupper($zone));
        // if(json_decode($getResponse)->http_status != 200)
        // {
        //     return $this->ReturnResponse(true, "Impossible de trouver la liste des offres ", [], 404);
        // }
        return $this->ReturnResponse(true, "Liste des offres ", [], 200);
    }

    public function customerRecharge(Request $request)
    {

        $validator = Validator::make(
            $request->all(),
            [
                'zone_name'         => 'required',
                //"customer_login"    => 'required',
                "subscription_name" => 'required',
            ]
        );

        // If Errors
        if ($validator->fails()) {
            return $this->ReturnResponse(false, $validator->errors(), [], 401);
        }

        $hotspotService = new HotspotService();

        // Exemple d'une requête PUT avec des données JSON
        $putData = array(
            'subscription_name' =>  $request->subscription_name
        );

        $zone = str_replace(' ', '+', $request->zone_name);

        $url = 'customer/refilling';

        $response = $hotspotService->put($url . '?zone_name=' . strtoupper($zone) . '&customer_login=' . $request->user()->email, $putData);

        if (json_decode($response)->http_status != 200) {
            return $this->ReturnResponse(false, "Impossible de recharger cet utilisateur ", [], 404);
        }

        return $this->ReturnResponse(true, "Rechargement du client efféctué avec succès", [json_decode($response)], 200);
    }

    public function createCustomer(Request $request)
    {

        $validator = Validator::make(
            $request->all(),
            [
                "zone_name"             => 'required',
                "subscription_name"     => 'required',
                "customer_firstname"    => 'required',
                "customer_lastname"     => 'required',
                "customer_email"        => 'required',
            ]
        );

        // If Errors
        if ($validator->fails()) {
            return $this->ReturnResponse(false, $validator->errors(), [], 401);
        }

        $hotspotService = new HotspotService();

        $postData = array(
            'zone_name'                 => $request->zone_name,
            'subscription_name'         => $request->subscription_name,
            'customer_firstname'        => $request->customer_firstname,
            'customer_lastname'         => $request->customer_lastname,
            'customer_email'            => $request->customer_email,
            'customer_mobile_number'    => $request->customer_mobile_number,
            'customer_password'         => $request->customer_password
        );

        $url = 'customer';
        //dd($postData);
        $response = $hotspotService->post($url, $postData);

        if (json_decode($response)->http_status != 201) {
            return $this->ReturnResponse(false, "Impossible de créer cet utilisateur sur le hotspot ", [], 404);
        }

        return $this->ReturnResponse(true, "Création de l'utiisateur sur le Hotspot", [json_decode($response)]);
    }

    public function customerRefills(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'zone_name'         => 'required',
                "customer_login"    => 'required',
            ]
        );

        // If Errors
        if ($validator->fails()) {
            return $this->ReturnResponse(false, $validator->errors(), [], 401);
        }

        $zone = str_replace(' ', '+', $request->zone_name);
        $hotspotService = new HotspotService();

        $url = 'customer/refills';

        $getResponse = $hotspotService->get($url . '?zone_name=' . strtoupper($zone) . '&customer_login=' . $request->customer_login);

        if (json_decode($getResponse)->http_status != 200) {
            return $this->ReturnResponse(false, "Impossible d'avoir la liste des recharges sur le hotspot ", [], 404);
        }

        return $this->ReturnResponse(true, "La liste des recharges sur le Hotspot", [json_decode($getResponse)]);
    }
}
