<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Psy\CodeCleaner\FunctionReturnInWriteContextPass;
use Illuminate\Support\Facades\Session;

class ServiceRequestController extends Controller
{
    //
    public function index()
    {
        $email = session('email');
        $userName = session('refDataName');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $url = ApiBaseUrl()['url'] . filterAPI()['url'];
        $data = [
            "componentConfig" => [
                "moduleName" => "Service Inquiry",
                "productID" => ApiBaseUrl()['productID'],
                "clientID" => ApiBaseUrl()['clientID'],
                "aspectType" => "Request Form",
                "query" => [
                    "aspectType" => "Request Form",
                    "memberId" => session('id')
                ],
                "userName" => $userName,
                "skip" => 0,
                "next" => 1020
            ]
        ];
        $jsonData = json_encode($data);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

        $token = session('token');
        $headers = [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if ($result === false) {
            echo 'Curl error: ' . curl_error($ch);
            // Handle curl error appropriately
        } else {
            $response = json_decode($result);

            if ($response->statusCode == 1) {


                // usort($response->data, 'sortByTimestampDesc');

                $data['myServiceRequests_data'] = $response->data;


                // echo '<pre>';
                // print_r($data['myServiceRequests_data']);
                // die();

                $data['page'] = 'MY-SERVICE-REQUEST';
                $data['title'] = 'MY SERVICE REQUEST';
                $data['header'] = 'MY SERVICE REQUEST';
                return view('admin/my-service-request', $data);
            } else {

                $data['err_msg'] = $response->message;
                $data['page'] = 'MY-SERVICE-REQUEST';
                $data['title'] = 'MY SERVICE REQUEST';
                $data['header'] = 'MY SERVICE REQUEST';
                return view('admin/my-service-request', $data);
            }
        }

        curl_close($ch);
    }

    public function ServiceRequest()
    {

        $data['page'] = 'Service-Request';
        $data['header'] = 'REQUEST A SERVICE';
        $data['GetState'] = GetState();
        $userDetails = getUserDetails();
        $preferredLanguage = getPreferredLanguage();
        $PriestData = $this->getPriestData();
        $preferredLocations = getPreferredLocations();

        $data['userDetails'] = $userDetails->data[0];
        $data['preferredLanguage'] = $preferredLanguage->data;
        $data['preferredLocations'] = $preferredLocations->data;
        $data['PriestData'] = $PriestData->data;


        // $this->mongo_db2->where(['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => 'IN-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE']);

        $filter['query'] = ['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => 'IN-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE'];
        $array1 = ['businessdata'];

        // $this->mongo_db2->where(['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => 'AWAY-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE']);
        $filter['query'] = ['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => 'AWAY-TEMPLE', 'sourceTypes' => 'WEBSITE', 'status' => 'ACTIVE'];
        $array2 = ['businessdata'];

        $data['services'] = array_merge($array1, $array2);

        return view('admin/request-a-service', $data);
    }

    public function getPriestData()
    {
        $userName = session('refDataName');
        $ch = curl_init();

        // Disable SSL verification (not recommended in production)
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        // Construct the request payload
        $requestData = [
            "componentConfig" => [
                "moduleName" => "Contacts",
                "productID" => ApiBaseUrl()['productID'],
                "clientID" => ApiBaseUrl()['clientID'],
                "aspectType" => "Member Directory",
                "query" => [
                    "aspectType" => "Member Directory",
                    "memberTypes" => "PRIEST",
                    "status" => "ACTIVE"
                ],
                "userName" => $userName,
                "skip" => 0,
                "next" => 1020
            ]
        ];

        // Set request URL and options
        curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . filterAPI()['url']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

        // Set headers including authorization token
        $token = session('token');
        $headers = [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json'
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the request
        $result = curl_exec($ch);

        // Check for errors
        if (curl_errno($ch)) {
            // Handle error
            $error = 'Error: ' . curl_error($ch);
            curl_close($ch);
            return $error;
        }

        // Close curl session
        curl_close($ch);

        // Decode and return the response
        return json_decode($result);
    }


    //Service a request  GetServicesByCategory

    public function GetServicesByCategory(Request $request)
    {
        $currency = getCurrencySymbol();

        $serviceCatTypes = $request->param;
        if ($serviceCatTypes == 'aparakarya') {
            $serviceCatTypes = 'SHRAADHAM';
        }
        $filter['query'] = ['aspectType' => 'ServiceSetup', 'serviceCategoryTypes' => $serviceCatTypes, 'sourceTypes' => 'WEBSITE', 'bookingType' => 'SERVICE REQUEST', 'status' => 'ACTIVE'];

        $data =  getServiceRequestData($filter);
        $html = '';
        $html .= '<option value=" " selected disabled>Please Select Service</option>';
        foreach ($data as $item) {
            $html .= '<option value="' . $item['refDataName'] . '"  serviceId="' . $item['_id'] . '" startDate="' . $item['startDate'] . '" startTime="' . $item['startTime'] . '" serviceType="' . $item['serviceTypes'] . '" serviceAmount="' . $item['serviceAmount'] . '">' . $item['refDataName'] . '(' . $currency . ' ' . $item['serviceAmount'] . ')' . '</option>';
        }

        $html .= '<option value="Other" serviceId="0" startdate="" starttime="" servicetype="OTHERS" serviceCategoryType="AWAY-TEMPLE" serviceamount="0.0">Other($ 0.00)</option>';
        echo $html;
    }

    // Add service request

    public function addServiceRequest(Request $request)
    {
        //return $request->all();
        // $redirect_url =$request->page_name == 'outside-temple' ?  'services/request/outside-temple' :  ($request->page_name == 'aparakarya' ? 'services/request/aparakarya' : 'services/serviceRequest');
        $gotra = $request->gotra;
        $stars = $request->stars;
        $rashi = $request->rashi;
        if (!empty($gotra) || !empty($stars) || !empty($rashi)) {



            $Id = session('id');
            $userName = session('refDataName');

            $moduleName = customerLogin()['moduleName'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

            // Assuming ApiBaseUrl() and postAPI() functions return an array with 'url' key
            $apiBaseUrl = ApiBaseUrl()['url'];
            $postApiUrl = postAPI()['url'];

            // Assuming $Id, $gotra, $stars, $rashi, $userName are defined elsewhere
            $data = array(
                "_id" => $Id,
                "dataJson" => array(
                    "gotraName" => $gotra,
                    "Nakshtra" => $stars,
                    "rashi" => $rashi
                ),
                "componentConfig" => array(
                    "moduleName" => "Contacts",
                    "productID" => ApiBaseUrl()['productID'],
                    "clientID" => ApiBaseUrl()['clientID'],
                    "userName" => $userName
                )
            );

            $data_string = json_encode($data);

            curl_setopt($ch, CURLOPT_URL, $apiBaseUrl . $postApiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

            $token = session('token');
            $headers = array(
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $result = curl_exec($ch);

            if ($result === false) {
                echo 'Curl error: ' . curl_error($ch);
            } else {
                $response = json_decode($result);
                // Process $response as needed
            }

            curl_close($ch);
        }

        $fname = $request->fname;
        $lname = $request->lname;

        $email = $request->email;

        $email  = $email != '' ? base64_encode($email) : '';
        $phoneNumber = $request->phoneNumber;
        $phoneNumber  = $phoneNumber != '' ? base64_encode($phoneNumber) : '';

        $streetAddress = $request->streetAddress;


        $priestName = $request->priestName;
        $priestEmail = $request->priestEmail;
        $priestEmail  = $priestEmail != '' ? base64_encode($priestEmail) : '';
        $priestPhone = $request->priestPhone;
        $priestPhone  = $priestPhone != '' ? base64_encode($priestPhone) : '';
        $priestId = $request->priestId;


        $serviceDate = $request->serviceDate;
        $serviceTime = $request->serviceTime;

        // $preferredLanguage = $this->input->post('preferredLanguage');
        $preferredLocation = $request->preferredLocation;

        $serviceName = $request->serviceName;

        $addtionalInfo = $request->addtionalInfo;
        $serviceType = $request->serviceType;
        $serviceAmount = $request->serviceAmount;
        $serviceId = $request->serviceId;
        $preferredLanguage = @getUserDetails()->data[0]->languagePreferenceName;


        $serviceAddress = $request->serviceAddress;

        if ($serviceAddress != '') {
            $serviceAddress = $request->serviceAddress;
        } else {
            $serviceAddress == '';
        }

        $isConfirmed = ($priestName != 'Any Priest') ? 'true' : 'false';
        if ($serviceName == 'Other') {
            $serviceName = $request->serviceDetails;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // Set to 2 for strict verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // Set to true for SSL verification

        // Set API URL
        $url = ApiBaseUrl()['url'] . addServiceRequest()['url'];
        curl_setopt($ch, CURLOPT_URL, $url);

        // Prepare POST data
        $data = array(
            "memberId" => session('id'),
            "serviceId" => $serviceId,
            "serviceRequestName" => $fname . " " . $lname,
            "prsnEmail" => $email,
            "prsnPhone" => $phoneNumber,
            "clientId" => ApiBaseUrl()['clientID'],
            "serviceDate" => $serviceDate,
            "serviceTime" => $serviceTime,
            "serviceLocationName" => $preferredLocation,
            "serviceAddress" => $serviceAddress,
            "serviceName" => $serviceName,
            "serviceCategoryTypes" => $preferredLocation,
            "serviceTypes" => $serviceType,
            "serviceAmount" => $serviceAmount,
            "languagePreferenceName" => $preferredLanguage,
            "notes" => $addtionalInfo,
            "requestForPriestName" => $priestName,
            "priestEmail" => $priestEmail,
            "priestPhone" => $priestPhone,
            "requestedPriestId" => $priestId,
            "isConfirmed" => $isConfirmed,
            "foodType" => "",
            "package" => "",
            "extraFood" => "",
            "etShraadhamFor" => "",
            "ettithiDetail" => "",
            "source" => "WEBSITE",
            "notificationEmailName" => "YES"
        );

        $data_string = json_encode($data);

        // Set cURL options
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

        // Set headers
        $headers = array(
            'Authorization: Bearer ' . session('token'),
            'Content-Type: application/json'
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // Execute the request
        $result = curl_exec($ch);

        // Check for errors
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        } else {
            // Handle response
            $response = json_decode($result);
            //return $response;
            if ($response->statusCode == 1) {
                $request->session()->flash('success', '<div class="alert alert-success alert-dismissible fade show"><strong>Success!</strong> Your Service Request has been successful.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');


                if ($request->has('source') && $request->input('source') == 'SERVICES-PAGE') {
                    echo '<script type="text/javascript">
                        alert("Service Request has been submitted successfully!!");
                        if (confirm("Would you like to go to the My Service Requests page?")) {
                            window.location.href="' . route('/admin.my-service-request') . '";
                        } else {
                            window.location.href="' . route('services') . '";
                        }
                        </script>';
                } else {
                    return redirect()->route('admin.my-service-request');
                }
            }
            // Further processing of the response
        }

        // Close cURL session
        curl_close($ch);
    }
}
