<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Http;

class PriestFormContoller extends Controller
{
    //
    public function index()
    {
        $data['header_data'] = getWebSyncsData('Header Settings', 'headerSettings', '');

        $data['page'] = 'PRIEST FORM';
        $data['title'] = 'PRIEST RESQUEST FORM';
        return view('priest-request', $data);
    }
    public function submitPriestRequest(Request $request)
    {
        // return $request->all();
        $SpecifyPurpose = $request->input('specify');
        $Specializationdetails = $request->input('sd');
        $Event = $request->input('Event');
        $NoofPriest = $request->input('priestname');
        $StartDate = $request->input('startDailyDate');
        $EndDate = $request->input('endDailyDate');
        $StartTime = $request->input('eventTime');
        $Endtime = $request->input('eventEndTime');
        $Location = $request->input('Location');
        $Language = $request->input('Lanuage');
        $imageSrc1 = $request->file('ContractAgreementDoc');
        $salaryInfo = $request->input('Sallery');
        $imageSrc2 = $request->file('uploadresume');
        $ContactName = $request->input('cname');
        $Email = $request->input('email');
        $Phonenumber = $request->input('Phone');
        $TempleName = $request->input('tname');
        $TempleAddress = $request->input('templeAddress');
        $AccommodationProvided = $request->input('AccommodationProvided');
        $TravelExpenseInclude = $request->input('TravelExpenseInclude');

        $imageSources = array($imageSrc1, $imageSrc2);

        $responses = array(); // Initialize an array to store responses

        foreach ($imageSources as $index => $imageSrc) {
            $url = ApiBaseUrl()['url'] . 'api/upload/docsmany';
            $file_field_name = 'image';
            $file_mime_type = $imageSrc->getClientMimeType();
            $file_path = $imageSrc->getRealPath();
            $file_name = $imageSrc->getClientOriginalName();

            $response = Http::attach(
                $file_field_name,
                file_get_contents($file_path),
                $file_name,
                ['Content-Type' => $file_mime_type]
            )->withOptions([
                'verify' => false,
            ])->post($url, ['type' => 'profile']);



            $decodedResult = json_decode(json_encode($response->json()), true);
            // print_r($decodedResult);

            if (isset($decodedResult['result']['message']['path'])) {
                $pathString = $decodedResult['result']['message']['path'];
                $responses[] = json_decode($pathString, true);
            } else {
                $responses[] = array('error' => 'Path not found in response');
            }
        }

        // print_r($responses);

        // Handle responses as needed

        // return response()->json($responses);

        //return $responses[0]['path'];


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        // curl_setopt($ch, CURLOPT_URL, 'API:  https://aspgen.vaaptech.com:9000/api/appgen/addAPI');
        curl_setopt($ch, CURLOPT_URL, ApiBaseUrl()['url'] . addAPI()['url']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $postData = array(
            "componentConfig" => array(
                "moduleName" => "Priest Request Form",
                "aspectType" => "Priest Request Form",
                "productID" => ApiBaseUrl()['productID'],
                "clientID" => ApiBaseUrl()['clientID'],
                "userName" => "ravi6905"
            ),
            "dataJson" => array(
                "refDataName" => "Puja Service",
                "refDataNameId" => "",
                "specializationDetail" => $Specializationdetails,
                "specializationDetailId" => "",
                "event" =>  $Event,
                "eventId" => "",
                "noOfPriest" =>  $NoofPriest,
                "noOfPriestId" => "",
                "startDate" =>   $StartDate,
                "startDateId" => "",
                "endDate" => $EndDate,
                "endDateId" => "",
                "startTime" => $StartTime,
                "startTimeId" => "",
                "endTime" => $Endtime,
                "endtimeid" => "",
                "location" => $Location,
                "locationid" => "",
                "language" => $Language,
                "languageid" => "",
                "contractagreement" => $responses[0][0]['paths'],
                "contractagreementid" => "",
                "salaryinfo" => $salaryInfo,
                "salaryinfoid" => "",
                "resumeupload" => $responses[1][0]['paths'],
                "resumeuploadid" => "",
                "contactname" => $ContactName,
                "contactnameid" => "",
                "email" => $Email,
                "emailId" => "",
                "phone" =>  $Phonenumber,
                "phoneId" => "",
                "templeName" => $TempleName,
                "templeNameId" => "",
                "templeAddress" => $TempleAddress,
                "templeAddressId" => "",
                "accommodationProvided" => $AccommodationProvided,
                "accommodationProvidedId" => "63943c2c8ffd31720fca4276",
                "expenseIncluded" => $TravelExpenseInclude,
                "expenseIncludedId" => "63943c2c8ffd31720fca4276"
            )
        );
        $postFields = json_encode($postData);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

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

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

        // Assuming $responses is an array
        $response = json_decode($result, true);
        // print_r($response);

        // die;

        if (isset($response['statusCode']) && $response['statusCode'] == 1) {
            session::flash('success', '<div class="alert alert-success alert-dismissible fade show text-center">Priest Request has been submitted successfully! Our management team will contact you as soon as possible!!<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
            return redirect()->back();
        } else {
            session::flash('failure', '<div class="alert alert-warning alert-dismissible fade show text-center">Something Went Wrong!<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>');
            return redirect()->back();
        }
    }
}
