<?php
defined('BASEPATH') or exit('No direct script access allowed');

class PriestForm extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    public function index()
    {
        $data['page'] = 'PRIEST FORM';
        $data['title'] = 'PRIEST RESQUEST FORM';
        $this->load->view('priest-request', $data);
    }

    function submitPriestRequest()
    {

        $SpecifyPurpose = $this->input->post('specify');
        $Specializationdetails = $this->input->post('sd');
        $Event = $this->input->post('Event');
        $NoofPriest = $this->input->post('priestname');
        $StartDate = $this->input->post('startDailyDate');
        $EndDate = $this->input->post('endDailyDate');
        $StartTime = $this->input->post('eventTime');
        $Endtime = $this->input->post('eventEndTime');
        $Location = $this->input->post('Location');
        $Language = $this->input->post('Lanuage');
        $imageSrc1 = $this->input->post('ContractAgreementDoc');
        $salaryInfo = $this->input->post('Sallery');
        $imageSrc2 = $this->input->post('uploadresume');
        $ContactName = $this->input->post('cname');
        $Email = $this->input->post('email');
        $Phonenumber = $this->input->post('Phone');
        $TempleName = $this->input->post('tname');
        $TempleAddress = $this->input->post('templeAddress');
        $AccommodationProvided = $this->input->post('AccommodationProvided');
        $TravelExpenseInclude = $this->input->post('TravelExpenseInclude');


        $imageSrc1 = 'ContractAgreementDoc';
        $imageSrc2 = 'uploadresume';

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

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

        foreach ($imageSources as $index => $imageSrc) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

            $url = ApiBaseUrl()['url'] . 'api/upload/docsmany';

            // Dynamically set file parameters based on the current index
            $file_field_name = 'image';
            $file_path = $_FILES[$imageSrc]['tmp_name'];
            $file_mime_type = $_FILES[$imageSrc]['type'];

            $file = new CURLFile($file_path, $file_mime_type, basename($file_path));

            $post = array(
                $file_field_name => $file,
                'type' => 'profile'
            );

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

            $result = curl_exec($ch);

            if (curl_errno($ch)) {
                echo 'cURL Error: ' . curl_error($ch);
                $responses[] = array('error' => curl_error($ch));
            } else {

                $decodedResult = json_decode($result, 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');
                }
            }

            curl_close($ch);
        }







        $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 = $this->session->userdata('token');
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoicnB1bGlwYWtAZ21haWwuY29tIiwiZXhwIjoxNzA0NjE0OTE3LCJpYXQiOjE3MDIwMjI5MTd9.R2BObIT6BFDGy2ZbK0NyZ-7dTDRsjaUsRfzSMGTvyAA';
        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['statusCode']);

    //    die;

       if (isset($response['statusCode']) && $response['statusCode'] == 1) {
        $this->session->set_flashdata('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>');
        redirect(base_url('priest-request-form'));
    } else {
        $this->session->set_flashdata('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>');
        redirect(base_url('priest-request-form'));
    }


    }
}
