<?php

namespace App\Http\Controllers\Admin\Api;

use App\Classes\Calendly;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redirect;

class CalendlyController extends Controller
{
    public function getCalendlyAuthUrl()
    {
        $calendly = new Calendly();
        $url =  $calendly->authUrl();
        return response()->json(['url' => $url]);
    }
    public function getRedirectCode(Request $request)
    {
        $calendly = new Calendly();
        $calendly->authorize($request->input("code"));
        return redirect("https://crm.rejuvallife.com/build/admin/dashboard");
    }
    public function getEvent(Request $request)
    {
        $calendly = new Calendly();
        $events = $calendly->eventTypes();
        $final_event = [];
        foreach ($events as $event) {
            $array = [];
            $array['slug'] = $event['slug'];
            $array['uri'] = $event['uri'];
            $array['type'] = $event['type'];
            array_push($final_event, $array);
            //$final_event[] +=  $array;
        }
        return response()->json(['message' => 'Admin has been authenticated.', 'events' => $final_event], 200);
    }
    public function setEvent(Request $request)
    {
        $uri = $request->input('url');
        $calendly = new Calendly();
        $calendly->setEventUri($uri);
        return response()->json(['message' => 'Event URI selected.'], 200);
    }
    public function resetEventUri()
    {
        $calendly = new Calendly();
        $calendly->resetEventUri();
        return response()->json(['message' => 'Event URI reset!.'], 200);
    }

    public function getAvailableDates(Request $request)
    {
        $setting = Setting::find(1);
        $month =  $request->input("month");
        $timezone =  $request->input("timezone");

        $calendly = new Calendly();

        $slots = $calendly->getAvailableDates($setting->event_type, $month, $timezone);

        return response()->json(['slots' => $slots], 200);
    }
    public function generateHexString($length = 32)
    {
        return bin2hex(random_bytes($length / 2));
    }
    public function generateRandomString($length = 37)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function bookSchedule(Request $request)
    {
        $referel = $url = $request->input("url");
        $patient_email = $request->input("patient_email");
        $patient_name = $request->input("patient_name");
        $timezone = $request->input("timezone");
        $calendly = new Calendly();

        $attempts = 0;
        $maxAttempts = 3;

        while ($attempts < $maxAttempts) {
            $response = $calendly->bookEvent($url, $patient_name, $patient_email, $timezone);
            $response = json_decode($response, true);

            if ($response && isset($response["event"]['start_time'])) {
                return response()->json(['success' => 'Event has been booked. ' . $response["event"]['start_time']], 200);
            }

            $attempts++;
        }

        return response()->json(['error' => 'Failed to complete the request after ' . $maxAttempts . ' attempts', 'response' => $response], 400);
    }
}
