<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Request;

use App\Staff;
use App\Model\StaffDetail;
use App\Model\Docket;
use App\Model\WorkOrder;
use App\Model\Company;
use App\Model\Form;
use App\Model\PackageDetail;
use App\Model\Subscriber;
use App\Model\FormStatus;

use Carbon\Carbon;


class StoreDocket implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $request, $do, $nature_work, $staff, $signature;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(array $request, $do, $nature_work, $staff, $signature)
    {
        //
        $this->request = $request;
        $this->do = $do;
        $this->nature_work = $nature_work;
        $this->staff = $staff;
        $this->signature = $signature;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(Docket $docket)
    {
        $note = '';
        $mac_router ='';
        $type_testing ='';
        if(isset($this->request['Note']) || ($this->request['mac_router']) || ($this->request['type_testing'])){
            $note = $this->request['Note'];
            $mac_router = $this->request['mac_router'];
            $type_testing = $this->request['type_testing'];
        }
        
        $docket->work_order_id = $this->request['wo'];
        $docket->docket_id = $this->do;
        $docket->nature_work = $this->nature_work;
        $docket->installer_id = $this->staff;
        $docket->end_job = Carbon::now()->toDateTimeString();
        $docket->router_serial_number = $this->request['router_serial_number'];
        $docket->mac_router = $mac_router;
        $docket->cable_read = $this->request['cable_read'];
        $docket->condition = $this->request['condition'];
        $docket->type_testing = $type_testing;
        $docket->Note = $note;
        $docket->Rating1 = $this->request['Rating1'];
        $docket->Rating2 = $this->request['Rating2'];
        $docket->Rating3 = $this->request['Rating3'];
        $docket->modem_sn = $this->request['modem_sn'];
        $docket->customer_signature = $this->signature;

        $work_order = WorkOrder::where('wo',$this->request['wo'])->first();
        $work_order->docket()->save($docket);
        $work_order->status = 'Completed';
        $work_order->docket_id = $this->do;
        $work_order->save();

        $fm = Form::where('_id',$work_order->_id)->first();
        $stat = new FormStatus();
        $stat->form_id = $fm->_id;
        $stat->status_id = 8;
        $stat->date = new \MongoDB\BSON\UTCDateTime(time()*1000);
        $stat->status = 'Completed';
        $stat->desc = 'This work order already been completed';
        $fm->formstatus()->save($stat);
    }
}
