<?php

namespace Spark2d;

use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;

/**
 * Class Spark2dZoho
 * @package Spark2d
 */
class Spark2dZoho {

	/**
	 * @var
	 */
	private $token;

	/**
	 * Spark2dZoho constructor.
	 */
	public function __construct() {
		$options     = get_option( 'spark2dzoho_definitions' );
		$this->token = $options['SPARK2D_ZOHO_ACCESS_TOKEN'];
		add_shortcode( "zoho_render_opportunities", array( $this, "render_shortcode" ) );
		
		add_shortcode( "zohospark_field", array( $this, "create_zohosparkfield_shortcode" ) );
		add_shortcode( "zohospark_form", array( $this, "create_zohosparkform_shortcode" ) );
		add_shortcode( "zohospark_form_spontaneous", array( $this, "create_zohosparkformspontaneous_shortcode" ) );
		
		add_shortcode( "zohospark_comunity", array( $this, "create_zohosparkcomunity_shortcode" ) );
	}

	/**
	 * @return false|string
	 */
	public function render_shortcode() {

		/**
		 * get style
		 */
		wp_enqueue_script('jquery');
		ob_start();
		$this->get_template( 'style' );
		$style = ob_get_clean();

		/**
		 * get html
		 */
		 
		if ( isset( $_POST['submit_spark2d_zoho_form_field'] ) and wp_verify_nonce( $_POST['submit_spark2d_zoho_form_field'],
				'submit_spark2d_zoho_form' ) ) {
			$html = $this->submit_form();
		} elseif ( $_GET["opportunity_id"] ) {
			$html = $this->render_form();
		} else {
			$html = $this->render_opportunities_table();
		}

		return $style . $html;
	}
	
	public function create_zohosparkfield_shortcode($atts) {
	    $atts = shortcode_atts(
    		array(
    			'field' => '',
    			'type' => '',
    		),
    		$atts,
    		'zohospark_field'
    	);
    
    	$field = $atts['field'];
    	$type = $atts['type'];
    	
    	ob_start();
		$opportunity = $this->get_opportunity( $_GET["opportunity_id"] );
    	
    	if ( $opportunity[$field] ) {
    	    if ( $type == 'li' ) {

    	        $output = '<ul class="zohoul">';
                $items = explode('*', $opportunity[$field]);
                foreach ($items as $item) {
                    if ( $item ) {
                        $output .= '<li>' . $item . '</li>';
                    }

                }  
                $output .= '</ul>';
                echo $output;
    	    } else {
    	        echo strip_tags( $opportunity[$field] );
    	    }

    	} else {
    	    echo 'Field not found!';
    	}
    	
		return ob_get_clean();
	}
	
	public function create_zohosparkform_shortcode($atts) {
	    wp_enqueue_script('jquery');
		ob_start();
		$this->get_template( 'style' );
		$style = ob_get_clean();
		
		if ( isset( $_POST['submit_spark2d_zoho_form_field'] ) and wp_verify_nonce( $_POST['submit_spark2d_zoho_form_field'],
				'submit_spark2d_zoho_form' ) ) {
			$html = $this->submit_form();
		} elseif ( $_GET["opportunity_id"] ) {
			$html = $this->render_form();
		} 
		
		//$html .= var_dump(get_option( "spark2d_zoho_list_fields" ));
		
		return $style . $html;
	}
	
	public function create_zohosparkformspontaneous_shortcode($atts) {
	    
	    $atts = shortcode_atts(
    		array(
    			'id' => '',
    		),
    		$atts,
    		'zohospark_form_spontaneous'
    	);
    
    	$id = $atts['id'];
    	
    	wp_enqueue_script('jquery');
		ob_start();
		$this->get_template( 'style' );
		$style = ob_get_clean();
		
		if ( isset( $_POST['submit_spark2d_zoho_form_field'] ) and wp_verify_nonce( $_POST['submit_spark2d_zoho_form_field'],
				'submit_spark2d_zoho_form' ) ) {
			$html = $this->submit_form();
		} else {
			$html = $this->render_form_id($id);
		} 
		
		//$html = $this->render_form_id($id);
		return $style . $html;
    	
	    
	}
	
	public function create_zohosparkcomunity_shortcode($atts) {
	    wp_enqueue_script('jquery');
		ob_start();

        //change to template
        $opportunities = $this->get_opportunities();

        
        $html = '<section data-particle_enable="false" data-particle-mobile-disabled="false" class="elementor-section elementor-inner-section elementor-element elementor-element-4869755 elementor-section-boxed elementor-section-height-default elementor-section-height-default opportunities-zoho" data-id="4869755" data-element_type="section">
    				<div class="elementor-container elementor-column-gap-default">';
        $i = 0;
        foreach ( $opportunities as $opportunity ) {
            
            if ( $i < 3 ) {
                
                $banner = $opportunity['Image Site'];
                
                //var_dump($opportunity);

                if ( $banner <> NULL ) {
                    $url = $banner;
                } else {
                    $url = '/wp-content/uploads/2021/04/Mask-Group-3.png';
                }
                
                

                $html .= '
                
                        <div class="elementor-column elementor-col-33 elementor-inner-column elementor-element elementor-element-886ae97 opportunity-home" data-id="886ae97" data-element_type="column">
            			    <div class="elementor-widget-wrap elementor-element-populated">
            				    <div class="elementor-element elementor-element-173930d elementor-widget elementor-widget-image" data-id="173930d" data-element_type="widget" data-widget_type="image.default">
            				        <div class="elementor-widget-container">
            				            <a href="/job/?opportunity_id='.$opportunity["JOBOPENINGID"].'&opportunity='.rawurlencode($opportunity["Posting Title (em inglês)"]).'>" >
            							   <img width="368" height="368" src="'.$url.'" class="attachment-full size-full" alt="banner - '.$opportunity['Posting Title (em inglês)'].'" loading="lazy" srcset="">
            						    </a>
            						</div>
            				    </div>
            				    <div class="elementor-element elementor-element-9c03fae elementor-widget elementor-widget-heading" data-id="9c03fae" data-element_type="widget" data-widget_type="heading.default">
            				        <div class="elementor-widget-container job-title-container">
            				            <a href="/job/?opportunity_id='.$opportunity["JOBOPENINGID"].'&opportunity='.rawurlencode($opportunity["Posting Title (em inglês)"]).'>" >
            			                    <h3 class="elementor-heading-title elementor-size-default job-title">'.$opportunity['Posting Title (em inglês)'].'</h3>		
            			                </a>
            			            </div>
            				    </div>
            				    <div class="elementor-element elementor-element-38058f6 elementor-widget elementor-widget-heading" data-id="38058f6" data-element_type="widget" data-widget_type="heading.default">
            				        <div class="elementor-widget-container city-container">
            			                <h4 class="elementor-heading-title elementor-size-default city">'.$opportunity['City'].'</h4>
            			            </div>
            				    </div>
            				</div>
            		    </div>
                   ';
            }
            $i++;
        }
        $html .= ' </div>
                </section>';
                
              
        ob_get_clean();

		return $style . $html;
	}

	/**
	 * Render table of opportunities
	 * @return false|string
	 */
	public function render_opportunities_table() {
		ob_start();
		$opportunities = $this->get_opportunities();
		$this->get_template( 'opportunities-list', [ 'opportunities' => $opportunities ] );

		return ob_get_clean();
	}

	/**
	 * Render form
	 * @return false|string
	 */
	public function render_form() {
		ob_start();
		$opportunity = $this->get_opportunity( $_GET["opportunity_id"] );
		$fields      = $this->get_fields_list_candidates();
		$this->get_template( 'form', [ 'fields' => $fields, 'opportunity' => $opportunity ] );

		return ob_get_clean();

	}
	
	/**
	 * Render form from ID
	 * @return false|string
	 */
	 
	 public function render_form_id( $id_opportunity ) {
		ob_start();
		$opportunity = $this->get_opportunity( $id_opportunity );
		$fields      = $this->get_fields_list_candidates();
		$this->get_template( 'form', [ 'fields' => $fields, 'opportunity' => $opportunity ] );

		return ob_get_clean();

	}

	/**
	 * Submit form , send email customer and render success message
	 * @return false|string
	 */
	public function submit_form() {
		ob_start();
		$status = $this->publish_candidate( $_POST["zoho_form"], $_POST['opportunity_id'], $_POST["zoho_form_tabs"] );
		$this->get_template( 'result-submission', [ 'status' => $status ] );

		return ob_get_clean();
	}

	/**
	 * Get all fields in candidates module
	 * @return array|mixed|void
	 */
	public function get_fields_list_candidates() {
		try {
			if ( $last_sync = get_option( "spark2d_zoho_fields_last_sync" ) ) {
				if ( $last_sync >= Carbon::now()->subHour() ) {
					if ( $list_of_fields = get_option( "spark2d_zoho_list_fields" ) ) {
						if ( is_array( $list_of_fields ) ) {
							return $list_of_fields;
						}
					}
				}
			}
			$client         = new \Humantech\Zoho\Recruit\Api\Client\Client( $this->token );
			$fields         = $client->getFields( "Candidates" );
			$list_of_fields = array();
			foreach ( $fields as $section ) {
				foreach ( $section['FL'] as $field ) {
					$list_of_fields[ $section['dv'] ][ $field['dv'] ] = $field;
				}
			}
			update_option( "spark2d_zoho_list_fields", $list_of_fields, false );
			update_option( "spark2d_zoho_fields_last_sync", Carbon::now() );

			return $list_of_fields;
		} catch ( Exception $e ) {
			return array();
		}
	}

	/**
	 * Get list of opportunities in Zoho Recruit
	 * @return array
	 */
	public function get_opportunities() {
		try {
			$client                    = new \Humantech\Zoho\Recruit\Api\Client\Client( $this->token );
			$jobOpenings               = $client->getRecords( 'JobOpenings', array(
				"toIndex"   => 200,
				"fromIndex" => 1,
			) );
			$list_public_opportunities = array();

			$options     = get_option( 'spark2dzoho_definitions' );
			$nameWebsite = $options['SPARK2D_ZOHO_WEBSITE_NAME'];

			foreach ( $jobOpenings as $job_opening ) {
				if ( strpos( $job_opening['Available on websites'], $nameWebsite ) !== false
				     and $job_opening['Job Opening Status'] !== 'Preenchido' ) {
					$list_public_opportunities[] = $job_opening;
				}
			}
			update_option( "spark2d_zoho_opportunities", $list_public_opportunities, false );
			update_option( "spark2d_zoho_last_sync", Carbon::now() );

			return $list_public_opportunities;
		} catch ( Exception $e ) {
			return array();
		}
	}

	/**
	 * Return opportunity detail
	 *
	 * @param $id
	 *
	 * @return mixed|null
	 */
	public function get_opportunity( $id ) {
		$list = $this->get_opportunities();
		foreach ( $list as $item ) {
			if ( $item["JOBOPENINGID"] == $id ) {
				return $item;
			}
		}

		return null;
	}

	/**
	 * Create candidate and associate it with offer
	 *
	 * @param $data
	 * @param $opportunity_id
	 * @param $tabular_data
	 *
	 * @return bool
	 * @throws \GuzzleHttp\Exception\GuzzleException
	 */
	public function publish_candidate( $data, $opportunity_id, $tabular_data ) {
		$client = new \Humantech\Zoho\Recruit\Api\Client\Client( $this->token );
		//add info about candidate
		$response = $client->addRecords( 'Candidates', $data, [], "json" );
		if ( $response === "Record(s) added successfully" || $response === "Record(s) already exists" ) {
			$customer = $client->getSearchRecords( "Candidates", "Candidates(CANDIDATEID)",
				"(Email|=|{$data['Email']})" );
			if ( count( $customer ) == 1 ) {
				$candidate_id = $customer[0]["CANDIDATEID"];
			}
		}

		$xmlData          = '<Candidates>';
		$submeter_tabular = false;
		if ( $candidate_id ) {
			if ( count( $tabular_data["Experience"] ) > 0 ) {
				$xmlData .= '<FL val="Experience Details">';
				foreach ( $tabular_data["Experience"] as $index => $exp ) {
					if ( ! $exp["Occupation / Title"] ) {
						continue;
					}
					$xmlData   .= "<TR no=\"{$index}\">";
					$xmlData   .= "<TL val=\"Occupation / Title\"><![CDATA[{$exp["Occupation / Title"]}]]></TL>";
					$xmlData   .= "<TL val=\"Company\"><![CDATA[{$exp["Company"]}]]></TL>";
					$xmlData   .= "<TL val=\"Summary\"><![CDATA[{$exp["Summary"]}]]></TL>";
					$work_from = implode( "-", $exp["Work Duration_From"] );
					$work_to   = implode( "-", $exp["Work Duration_To"] );
					$xmlData   .= "<TL val=\"Work Duration_From\"><![CDATA[{$work_from}]]></TL>";
					$xmlData   .= "<TL val=\"Work Duration_To\"><![CDATA[{$work_to}]]></TL>";
					if ( $exp["I currently work here"] ) {
						$xmlData .= "<TL val=\"I currently work here\">true</TL>";
					}
					$xmlData          .= '</TR>';
					$submeter_tabular = true;
				}
				$xmlData .= '</FL>';
			}
			if ( count( $tabular_data["Education"] ) > 0 ) {
				$xmlData .= '<FL val="Educational Details">';
				foreach ( $tabular_data["Education"] as $index => $exp ) {
					if ( ! $exp["Institute / School"] ) {
						continue;
					}
					$xmlData   .= "<TR no=\"{$index}\">";
					$xmlData   .= "<TL val=\"Institute / School\"><![CDATA[{$exp["Institute / School"]}]]></TL>";
					$xmlData   .= "<TL val=\"Degree\"><![CDATA[{$exp["Degree"]}]]></TL>";
					$xmlData   .= "<TL val=\"Major / Department\"><![CDATA[{$exp["Major / Department"]}]]></TL>";
					$work_from = implode( "-", $exp["Duration_From"] );
					$work_to   = implode( "-", $exp["Duration_To"] );
					$xmlData   .= "<TL val=\"Duration_From\"><![CDATA[{$work_from}]]></TL>";
					$xmlData   .= "<TL val=\"Duration_To\"><![CDATA[{$work_to}]]></TL>";
					if ( $exp["Currently pursuing"] ) {
						$xmlData .= "<TL val=\"Currently pursuing\">true</TL>";
					}
					$xmlData          .= '</TR>';
					$submeter_tabular = true;
				}
				$xmlData .= '</FL>';
			}
			$xmlData .= '</Candidates>';
			$xmlData = trim( preg_replace( '/\s\s+/', ' ', $xmlData ) );

			$uploadToMedia = false;

			try {
				if ( $submeter_tabular ) {
					$client2        = new Client();
					$result_tabular = $client2->post( "https://recruit.zoho.com/recruit/internal/xml/Candidates/addTabularRecords",
						array(
							"query" => array(
								"authtoken" => $this->token,
								"id"        => $candidate_id,
								"xmlData"   => $xmlData
							)
						) );
				}
				if ( $_FILES["Resume"]["tmp_name"] ) {
					$file = $this->get_curl_value( $_FILES["Resume"]["tmp_name"], $_FILES["Resume"]["type"],
						$_FILES["Resume"]["name"] );
					$client->uploadFile( $candidate_id, "Resume", $file );

				}
				if ( $_FILES["CoverLetter"]["tmp_name"] ) {
					$file = $this->get_curl_value( $_FILES["CoverLetter"]["tmp_name"], $_FILES["CoverLetter"]["type"],
						$_FILES["CoverLetter"]["name"] );
					$client->uploadFile( $candidate_id, "Cover Letter", $file );
				}
				if ( $_FILES["Others"]["tmp_name"] ) {
					$file = $this->get_curl_value( $_FILES["Others"]["tmp_name"], $_FILES["Others"]["type"],
						$_FILES["Others"]["name"] );
					$client->uploadFile( $candidate_id, "Others", $file );
				}
			} catch ( Exception $e ) {
				/**
				 * Enable logs on file uploads
				 */
				$logFile   = get_option( 'spark2dzoho_logs', [] );
				$logFile[] = $e->getMessage();
				update_option( 'spark2dzoho_logs', $logFile );
				/**
				 * Upload file to media
				 */
				$uploadToMedia = true;
			}

			if($uploadToMedia) {
				try {
					require_once(ABSPATH . 'wp-admin/includes/image.php');
					require_once(ABSPATH . 'wp-admin/includes/file.php');
					require_once(ABSPATH . 'wp-admin/includes/media.php');

					if ( $_FILES["Resume"]["tmp_name"] ) {
						$image_description            = array(
							"post_title"    => "Resume for ".$data["Email"],
							"post_content" => "Resume for ".$data["Email"],
						);
						media_handle_upload( "Resume", null, $image_description );
					}
					if ( $_FILES["CoverLetter"]["tmp_name"] ) {
						$image_description            = array(
							"post_title"    => "Cover Letter for ".$data["Email"],
							"post_content" => "Cover Letter for ".$data["Email"],
						);
						media_handle_upload( "CoverLetter", null, $image_description );
					}
					if ( $_FILES["Others"]["tmp_name"] ) {
						$image_description            = array(
							"post_title"    => "Other File for ".$data["Email"],
							"post_content" => "Other File for ".$data["Email"],
						);
						media_handle_upload( "Others", null, $image_description );
					}
				}catch (Exception $e) {
				}
			}
		}

		//associate candidate to job opening
		if ( $candidate_id and $opportunity_id ) {
			$response2 = $client->associateJobopening( array( $opportunity_id ), array( $candidate_id ),
				[ "status" => "New" ] );
			if ( $response2 === "Candidate(s) associated successfully" ) {
				$this->send_email_candidate( $data["Email"], $data );

				return true;
			}
		}

		return false;
	}

	/**
	 * @param $filename
	 * @param $contentType
	 * @param $postname
	 *
	 * @return \CURLFile|string
	 */
	public function get_curl_value( $filename, $contentType, $postname ) {
		if ( function_exists( 'curl_file_create' ) ) {
			return curl_file_create( $filename, $contentType, $postname );
		}
		$value = "@{$this->filename};filename=" . $postname;
		if ( $contentType ) {
			$value .= ';type=' . $contentType;
		}

		return $value;
	}

	/**
	 * Send email to candidate
	 *
	 * @param $email
	 * @param $data
	 *
	 * @return bool
	 */
	public function send_email_candidate( $email, $data ) {
		try {
			ob_start();
			$this->get_template( 'email', [ 'email' => $email, 'data' => $data ] );
			$message = ob_get_clean();
			
			if ( $data["opportunity"] ) {
			    $subject = sprintf( __( 'Your application for %s at Hyphen', 'spark2dzoho' ),
				$_POST['opportunidade_name'] );
			} else {
			    $subject = sprintf( __( 'Your spontaneous application - Hyphen', 'spark2dzoho' ) );
			}
			
			
			$headers = array( 'Content-Type: text/html; charset=UTF-8', 'From: SPARK2D <careers@spark2d.com>' );
			wp_mail( $email, $subject, $message, $headers );

		} catch ( Exception $e ) {
		}

		return true;
	}

	/**
	 * Locate template
	 *
	 * @param $name
	 *
	 * @return mixed|void
	 */
	private function locate_template( $name ) {
		$filename = "$name.php";
		$template = locate_template(
			array(
				SPARK2D_ZOHO_TEMPLATE_PATH . $filename,
			)
		);
		if ( ! $template ) {
			$template = SPARK2D_ZOHO_TEMPLATE_DIR . $filename;
		}

		return $template;
	}

	/**
	 * Get template
	 *
	 * @param       $name
	 * @param array $args
	 *
	 * @return bool
	 */
	private function get_template( $name, $args = array() ) {
		if ( $args && is_array( $args ) ) {
			extract( $args );
		}
		$template = $this->locate_template( $name );
		if ( ! file_exists( $template ) ) {
			return false;
		}

		include $template;

		return true;
	}


}