<?php

namespace App\Jobs;

use App\Components\Functions;
use App\Models\Config;
use App\Models\ConfigHostel;
use App\Models\Contract;
use App\Models\Hostel;
use App\Models\Renter;
use Barryvdh\DomPDF\PDF;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\Html;

class SendMailContract implements ShouldQueue {
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	protected $contractId;
	protected $email;

	public function __construct( $contractId, $email = null ) {
		//
		$this->contractId = $contractId;
		$this->email      = $email;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle() {
		//
		$contractId = $this->contractId;
		$contract   = Contract::find( $contractId );
		if ( ! $contract ) {
			return;
		}

		$config           = Config::where( 'owner_id', $contract->hostel->owner_id )->first();
		$configHostel     = ConfigHostel::where('owner_id', $contract->hostel->owner_id)->where('hostel_id', $contract->hostel_id)->first();
		$contractTemplate = $config->contract;
		if ($configHostel) {
            $contractTemplate = $configHostel->contract;
        }
		$renter           = Renter::where( 'user_id', $contract->renter_id )->first();

		$contractTemplate = Functions::getContractTemplate( $contract, $contractTemplate, $renter );
        $contractTemplate = html_entity_decode($contractTemplate);
        $contractTemplate = preg_replace('/&(?!#?[a-z0-9]+;)/', '-', $contractTemplate);


		$phpWord = new PhpWord();
		$section = $phpWord->addSection();

		//Html::addHtml( $section, $contractTemplate );
        Settings::setPdfRendererPath(base_path('vendor/dompdf/dompdf'));
        Settings::setPdfRendererName('DomPDF');
		$dirName      = 'hop-dong/hostel-' . $contract->hostel->id . '/room-' . $contract->room->id;
		$objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter( $phpWord, 'Word2007' );


		if ( ! \File::exists( public_path( $dirName ) ) ) {
			\File::makeDirectory( public_path( $dirName ), 0777, true );
		}

		$docxDir = public_path( 'hop-dong/phong-' . str_slug( $contract->room->name ) . '-nha-tro-' . str_slug( $contract->hostel->name ) . '.docx' );
		//$objectWriter->save( $docxDir );
        //$content = IOFactory::load($docxDir);


        $pdfDir = public_path( 'hop-dong/phong-' . str_slug( $contract->room->name ) . '-nha-tro-' . str_slug( $contract->hostel->name ) . '.pdf' );
        $pdf = \App::make('dompdf.wrapper');

        $contractTemplate = str_replace('font-family:Times New Roman,Times,serif', 'font-family:DejaVu Serif', $contractTemplate);
        $pdf->loadHtml($contractTemplate, 'UTF-8')
          ->save($pdfDir);
//        $pdf = new PDF();
//        $pdfloadHTML($contractTemplate)
//            ->save( public_path( 'hop-dong/phong-' . str_slug( $contract->room->name ) . '-nha-tro-' . str_slug( $contract->hostel->name ) . '.pdf' ));

		if ( empty( $this->email ) ) {
			$renters = Renter::query()->select( \DB::raw( 'renters.*' ) )
			                 ->join( 'renter_rooms', 'renters.user_id', '=', 'renter_rooms.user_id' )
			                 ->whereNull( 'renter_rooms.deleted_at' )
			                 ->whereNotNull( 'renters.email' )
			                 ->where( 'renter_rooms.room_id', $contract->room->id )->get();

			if($contract->hostel->type_rent == Hostel::TYPE_RENT_EVERY)
            {
                $renters = Renter::query()->select( \DB::raw( 'renters.*' ) )
                    ->join( 'renter_rooms', 'renters.user_id', '=', 'renter_rooms.user_id' )
                    ->whereNull( 'renter_rooms.deleted_at' )
                    ->whereNotNull( 'renters.email' )
                    ->where( 'renter_rooms.contract_id', $contract->id )
                    ->get();
            }

			foreach ( $renters as $renter ) {


				\Mail::send( 'frontend3.mail.mail_contract', [
					'contract' => $contract
				], function ( $message ) use ( $contract, $dirName, $renter, $docxDir, $pdfDir ) {
					$message->to( $renter->email );
					if($contract->bed) {
                        $message->subject( 'Thông tin hợp đồng giường ' . $contract->bed->name .', phòng '.$contract->room->name. ', nhà trọ ' . $contract->hostel->name );
                    } else {
                        $message->subject('Thông tin hợp đồng phòng ' . $contract->room->name . ', nhà trọ ' . $contract->hostel->name);
                    }
					$message->attach( $pdfDir);
				} );
			}
		} else {
			$email = $this->email;
			\Mail::send( 'frontend3.mail.mail_contract', [
				'contract' => $contract
			], function ( $message ) use ( $contract, $dirName, $email, $docxDir, $pdfDir ) {
				$message->to( $email );
                if($contract->bed) {
                    $message->subject( 'Thông tin hợp đồng giường ' . $contract->bed->name .', phòng '.$contract->room->name. ', nhà trọ ' . $contract->hostel->name );
                } else {
                    $message->subject('Thông tin hợp đồng phòng ' . $contract->room->name . ', nhà trọ ' . $contract->hostel->name);
                }
				$message->attach( $pdfDir );
			} );
		}

	}
}
