<?php
namespace App\Services;

use App\Enums\GohighlevelLocations;
use App\Exceptions\RemoteException;
use App\Exceptions\ValidationException;
use App\Traits\ApiServicesTrait;
use Carbon\Carbon;
use Exception;

class CRMGLService
{
    use ApiServicesTrait;

    protected ApiService $api;
    protected $locationId;
    protected $calendarId;
    public function __construct()
    {
        $this->api = new ApiService(
            baseUrl: env("CRM_LCMEDIA_GLAPI_BASE_URL"),
            headers: [
                "Version" => env("CRM_LCMEDIA_GLAPI_Version"),
            ]
        );
    }

    public function setToken($token)
    {
        $this->api->setToken($token);
    }

    public function setCalendarId($calendarId)
    {
        $this->calendarId = $calendarId;
    }

    public function setLocationId($locationId)
    {
        $this->locationId = $locationId;
    }

    public function getGHLCalendars()
    {
        return $this->api->get("calendars/", [
            "locationId" => $this->locationId
        ])["data"];
    }

    public function getAvailableSlots(
        $startDateMiliSeconds = null,
        $endDateMiliSeconds = null,
        $startDate = null,
        $endDate = null,
        $timeZone = "America/New_York"
    )
    {
        $_StartDate = empty($startDateMiliSeconds) ? $this->getTimeInUnixMiliseconds($startDate): $startDateMiliSeconds;
        $_EndDate = empty($endDateMiliSeconds) ? $this->getTimeInUnixMiliseconds($endDate): $endDateMiliSeconds;

        return $this->api->get("calendars/" . $this->calendarId . "/free-slots", [
            "startDate" => $_StartDate,
            "endDate" => $_EndDate,
            "timezone" => $timeZone,
        ]);
    }

    public function getCustomer($email = null, $phone = null)
    {
        $params = [
            "locationId" => $this->locationId,
        ];
        if( isset($email) )
            $params["email"] = $email;

        if( isset($phone) )
            $params["number"] = $phone;

        return $contactsFetch = $this->api->get("contacts/search/duplicate", $params);
    }

    public function createAppointment(
        $contactId,
        $startTime,
    )
    {
        $appointment = $this->api->post("calendars/events/appointments", [
            "calendarId" => $this->calendarId,
            "contactId" => $contactId,
            "locationId" => $this->locationId,
            "title" => "Appointment created by AI Assistant",
            "startTime" => $startTime,
            "meetingLocationType" => "default",
            "appointmentStatus" => "new",
        ]);

        if( isset($appointment["error"]) ):
            $this->logErrors(message: 'Error creating an appointment on CRM System', response: $appointment);
            throw new Exception(
                message: $appointment["error"]["message"],
                code: 2,
            );
        endif;

        return $appointment;
    }

    public function createCustomer(
        $firstName,
        $lastName,
        $email,
        $phone,
    )
    {
        return $this->api->post("contacts", [
            "locationId" => $this->locationId,
            "firstName" => $firstName,
            "lastName" => $lastName,
            "email" => $email,
            "phone" => $phone,
        ]);
    }

    public function getContactById($contactId)
    {
        $params = [
            "locationId" => $this->locationId,
        ];

        $response = $this->api->get("contacts/" . $contactId, $params);

        if (isset($response["error"])) {
            $this->logErrors(message: 'Error fetching contact from CRM System', response: $response);
            throw new Exception(
                message: $response["error"]["message"] ?? "Error al obtener el contacto",
                code: 2,
            );
        }

        return $response["data"] ?? $response;
    }
















    protected function getTimeInUnixMiliseconds($datetime)
    {
        return Carbon::parse($datetime)->timestamp * 1000;
    }

}
