<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Job;
use App\Models\Client;
use App\Models\JobVendor;
use App\Models\Consultant;
use App\Models\Implementor;
use Illuminate\Http\Request;
use App\Models\ConsultantJob;
use App\Models\ConsultantAging;
use App\Models\VendorSubmission;
use App\Models\ConsultantComment;
use Illuminate\Support\Facades\DB;
use App\Models\SubmissionInterviewer;
use RealRashid\SweetAlert\Facades\Alert;

class VendorSubmissionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = VendorSubmission::with(['consultant', 'job', 'client', 'creater'])->whereCreated_by(auth()->user()->id)->whereActive(1)->get();
        $vendor_statuses = config('custom.vendor_statuses');

        return view('vendor-submissions.index', compact('list', 'vendor_statuses'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $vendor_companies = vendorCompanySelect();
        $vendors = [];
        $implementors = implementorSelect();
        $clients = clientSelect();
        $countries = countrySelect();
        $states = stateSelect();
        $cities = citySelect();
        $technologies = technologySelect();
        $interview_modes = config('custom.interview_modes');
        $employment_types = config('custom.employment_types');

        return view('vendor-submissions.create', compact('vendor_companies', 'vendors', 'implementors', 'clients', 'countries', 'states', 'cities', 'technologies', 'interview_modes', 'employment_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        // Save Client
            $client = new Client;
            $client->name = $request->client_name;
            $client->email = $request->client_email;
            $client->mobile = $request->client_mobile;
            $client->country_id = $request->client_country_id;
            $client->state_id = $request->client_state_id;
            $client->city_id = $request->client_city_id;
            $client->address = $request->client_address;
            $client->website = $request->client_website;
            $client->created_by = auth()->user()->id;
            $client->save();

        // Save Implementor
            if($request->implementor_name != '' && $request->implementor_contact_name != '' && $request->implementor_email != '' && $request->implementor_mobile != '') {            
                $implementor = new Implementor;
                $implementor->name = $request->implementor_name;
                $implementor->contact_name = $request->implementor_contact_name;
                $implementor->email = $request->implementor_email;
                $implementor->mobile = $request->implementor_mobile;
                $implementor->country_id = $request->implementor_country_id;
                $implementor->state_id = $request->implementor_state_id;
                $implementor->city_id = $request->implementor_city_id;
                $implementor->address = $request->implementor_address;
                $implementor->website = $request->implementor_website;
                $implementor->created_by = auth()->user()->id;
                $implementor->save();
            }

        // Save Job
            $job = new Job;
            $job->title = $request->job_title;
            $job->min_experience = $request->job_min_experience;
            $job->max_experience = $request->job_max_experience;
            $job->interview_mode = $request->job_interview_mode;
            $job->employment_type = $request->job_employment_type;
            $job->description = $request->job_description;
            $job->internal_message = $request->job_internal_message;
            $job->interview_address = $request->interview_address;
            $job->status = 0;
            $job->source = 'internal';
            $job->min_payrate = $request->payrate;
            $job->max_payrate = 0;
            $job->country_id = $request->job_country_id;
            $job->state_id = $request->job_state_id;
            $job->city_id = $request->job_city_id;
            $job->client_id = $client->id;
            $job->implementor_id = (isset($implementor->id))?$implementor->id:null;
            $job->technology_id = $request->technology_id;
            $job->created_by = auth()->user()->id;
            $job->save();        
        
        // Assign jobs to consultants
        if(count($request->consultant_id) != 0) {
            for ($i=0; $i < count($request->consultant_id); $i++) { 
                $cj = new ConsultantJob;
                $cj->consultant_id = $request->consultant_id[$i];
                $cj->job_id = $job->id;
                $cj->payrate = $request->payrate;
                $cj->ot_payrate = 0;
                $cj->status = 1; // Applied
                $cj->created_by = auth()->user()->id;
                $cj->save();

                // Add comments for students
                $ccmnt = new ConsultantComment;
                $ccmnt->consultant_id = $request->consultant_id[$i];
                $ccmnt->comment = 'Submitted to vendor';
                $ccmnt->user_id = auth()->user()->id;
                $ccmnt->save();

                // Save submission
                $submission = new VendorSubmission;
                $submission->consultant_id = $request->consultant_id[$i];
                $submission->job_id = $job->id;
                $submission->client_id = $client->id;
                $submission->created_by = auth()->user()->id;
                $submission->status = 'submitted';
                $submission->save();

                // Save Client Interviewer dettails
                if($request->client_interviewer_name != '') {
                    $sbIntr = new SubmissionInterviewer;
                    $sbIntr->vendor_submission_id = $submission->id;
                    $sbIntr->type = 1;
                    $sbIntr->name = $request->client_interviewer_name;
                    $sbIntr->email = $request->client_interviewer_email_id;
                    $sbIntr->mobile = $request->client_interviewer_mobile_number;
                    $sbIntr->save();
                }
                // Save implementor interviewer
                if($request->imp_interviewer_name != '') {
                    $sbIntr = new SubmissionInterviewer;
                    $sbIntr->submission_id = $submission->id;
                    $sbIntr->type = 2;
                    $sbIntr->name = $request->imp_interviewer_name;
                    $sbIntr->email = $request->imp_interviewer_email_id;
                    $sbIntr->mobile = $request->imp_interviewer_mobile_number;
                    $sbIntr->save();
                }
                // Save vendor interviewer
                if($request->vendor_interviewer_name != '') {
                    $sbIntr = new SubmissionInterviewer;
                    $sbIntr->vendor_submission_id = $submission->id;
                    $sbIntr->type = 3;
                    $sbIntr->name = $request->vendor_interviewer_name;
                    $sbIntr->email = $request->vendor_interviewer_email_id;
                    $sbIntr->mobile = $request->vendor_interviewer_mobile_number;
                    $sbIntr->save();
                }
            }
        }
        

        // Save Job Vendors
        if(count($request->vendor_company_id) != 0) {
            for($i=0; $i<count($request->vendor_company_id); $i++) {
                // Save Job vendors
                if($job->id) {
                    $jv = new JobVendor;
                    $jv->job_id = $job->id;
                    $jv->vendor_company_id = $request->vendor_company_id[$i];
                    $jv->vendor_id = $request->vendor_id[$i];
                    $jv->save();
                }
            }
        }       
        
        
        DB::commit();

        Alert('success', 'Vendor submission is successful');
        return redirect(route('vendor_submissions.index'));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\VendorSubmission  $vendorSubmission
     * @return \Illuminate\Http\Response
     */
    public function show(VendorSubmission $vendorSubmission)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\VendorSubmission  $vendorSubmission
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $vendor_submission = VendorSubmission::find($id);
        $vendor_companies = vendorCompanySelect();
        $vendors = [];
        $implementors = implementorSelect();
        $clients = clientSelect();
        $countries = countrySelect();
        $states = stateSelect();
        $cities = citySelect();
        $technologies = technologySelect();
        $interview_modes = config('custom.interview_modes');
        $employment_types = config('custom.employment_types');

        // Job
        $job = Job::with(['implementor', 'client'])->find($vendor_submission->job_id);
        // Client
        $client = Client::find($vendor_submission->client_id);
        // Consultants
        $consultant = Consultant::find($vendor_submission->consultant_id);
        // Job Vendors
        $jobVendors = JobVendor::with(['vendor', 'vendor_company'])->whereJob_id($vendor_submission->job_id)->get();
        // Submission vendor screening
        $vendor_screening = SubmissionInterviewer::whereType(1)->whereVendor_submission_id($id)->first();
        $implementor_screening = SubmissionInterviewer::whereType(2)->whereVendor_submission_id($id)->first();
        $client_screening = SubmissionInterviewer::whereType(3)->whereVendor_submission_id($id)->first();

        return view('vendor-submissions.edit', compact('vendor_companies', 'vendors', 'implementors', 'clients', 'countries', 'states', 'cities', 'technologies', 'interview_modes', 'employment_types', 'job', 'client', 'consultant', 'jobVendors', 'vendor_screening', 'implementor_screening', 'client_screening', 'vendor_submission'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\VendorSubmission  $vendorSubmission
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $vendor_submission = VendorSubmission::find($id);
        $job = Job::find($vendor_submission->job_id);
        $vendor_screening = SubmissionInterviewer::whereType(1)->whereVendor_submission_id($id)->first();
        $implementor_screening = SubmissionInterviewer::whereType(2)->whereVendor_submission_id($id)->first();
        $client_screening = SubmissionInterviewer::whereType(3)->whereVendor_submission_id($id)->first();

        DB::beginTransaction();
        // Save Client
            $client = Client::find($vendor_submission->client_id);
            $client->name = $request->client_name;
            $client->email = $request->client_email;
            $client->mobile = $request->client_mobile;
            $client->country_id = $request->client_country_id;
            $client->state_id = $request->client_state_id;
            $client->city_id = $request->client_city_id;
            $client->address = $request->client_address;
            $client->website = $request->client_website;
            $client->save();

        // Save Implementor
            if($request->implementor_name != '' && $request->implementor_contact_name != '' && $request->implementor_email != '' && $request->implementor_mobile != '') {            
                if(isset($job->implementor_id)) {
                $implementor = Implementor::find($job->implementor_id);
                } else {
                $implementor = new Implementor;
                $implementor->created_by = auth()->user()->id;
                }
                $implementor->name = $request->implementor_name;
                $implementor->contact_name = $request->implementor_contact_name;
                $implementor->email = $request->implementor_email;
                $implementor->mobile = $request->implementor_mobile;
                $implementor->country_id = $request->implementor_country_id;
                $implementor->state_id = $request->implementor_state_id;
                $implementor->city_id = $request->implementor_city_id;
                $implementor->address = $request->implementor_address;
                $implementor->website = $request->implementor_website;
                $implementor->save();
            }

        // Save Job
            $job = Job::find($vendor_submission->job_id);
            $job->title = $request->job_title;
            $job->min_experience = $request->job_min_experience;
            $job->max_experience = $request->job_max_experience;
            $job->interview_mode = $request->job_interview_mode;
            $job->employment_type = $request->job_employment_type;
            $job->description = $request->job_description;
            $job->internal_message = $request->job_internal_message;
            $job->interview_address = $request->interview_address;
            $job->status = 0;
            $job->source = 'internal';
            $job->min_payrate = $request->payrate;
            $job->max_payrate = 0;
            $job->country_id = $request->job_country_id;
            $job->state_id = $request->job_state_id;
            $job->city_id = $request->job_city_id;
            $job->client_id = $client->id;
            $job->implementor_id = (isset($implementor->id))?$implementor->id:null;
            $job->save();        
        
        // Save vendor interviewer
        if($request->vendor_interviewer_name != '') {
            if(isset($vendor_screening->id)) {
                $sbIntr = SubmissionInterviewer::find($vendor_screening->id);
            } else {
                $sbIntr = new SubmissionInterviewer;
            }
            $sbIntr->vendor_submission_id = $vendor_submission->id;
            $sbIntr->type = 1;
            $sbIntr->name = $request->vendor_interviewer_name;
            $sbIntr->email = $request->vendor_interviewer_email_id;
            $sbIntr->mobile = $request->vendor_interviewer_mobile_number;
            $sbIntr->save();
        }
        // Save implementor interviewer
        if($request->imp_interviewer_name != '') {
            if(isset($implementor_screening->id)) {
                $sbIntr = SubmissionInterviewer::find($implementor_screening->id);
            } else {
                $sbIntr = new SubmissionInterviewer;
            }
            $sbIntr->submission_id = $vendor_submission->id;
            $sbIntr->type = 2;
            $sbIntr->name = $request->imp_interviewer_name;
            $sbIntr->email = $request->imp_interviewer_email_id;
            $sbIntr->mobile = $request->imp_interviewer_mobile_number;
            $sbIntr->save();
        }
        // Save Client Interviewer dettails
        if($request->client_interviewer_name != '') {
            if(isset($client_screening->id)) {
            $sbIntr = SubmissionInterviewer::find($client_screening->id);
            } else {
                $sbIntr = new SubmissionInterviewer;
            }
            $sbIntr->vendor_submission_id = $vendor_submission->id;
            $sbIntr->type = 3;
            $sbIntr->name = $request->client_interviewer_name;
            $sbIntr->email = $request->client_interviewer_email_id;
            $sbIntr->mobile = $request->client_interviewer_mobile_number;
            $sbIntr->save();
        }
        
        DB::commit();

        Alert('success', 'Vendor submission updated successful');
        return redirect(route('vendor_submissions.index'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\VendorSubmission  $vendorSubmission
     * @return \Illuminate\Http\Response
     */
    public function destroy(VendorSubmission $vendorSubmission)
    {
        //
    }

    // Change to client interview
    public function saveClientInterview(Request $request)
    {
        // Replicate previous submission for history purpose
        $submission = VendorSubmission::find($request->vendor_submission_id);
        $submission = $submission->replicate();
        $submission->status = $request->consultant_status;
        $submission->active = 1;
        $submission->interview_date = $request->client_interview_date;
        $submission->interview_time = $request->client_interview_time;
        $submission->save();

        // Update previous submission
        $update = VendorSubmission::whereId($request->vendor_submission_id)->update(['active'=>0]);

        // Comment for consultant
        addConsultantComment($request->consultant_id, 'Submission status changed to Client interview');

        Alert('Success', 'Submission status changed');
        return 1;
    }

    // Join form
    public function joinForm(Request $request)
    {
        $submission = VendorSubmission::with(['consultant', 'job', 'client', 'creater'])->whereId($request->submission_id)->first();

        return view('vendor-submissions.join-form', compact('submission'));
    }

    // Saving Submission Join status
    public function saveSubmissionJoin(Request $request)
    {
        DB::beginTransaction();
        $tasks = VendorSubmission::find($request->submission_id);
        $newSubmission = $tasks->replicate();
        $newSubmission->status = 'joined';
        $newSubmission->active = 1;
        $newSubmission->push();
        
        $update = VendorSubmission::whereId($request->submission_id)->update(['active'=>0]);

        // Saving Consultant Jobs data
        $cj = new ConsultantJob;
        $cj->consultant_id = $request->consultant_id;
        $cj->job_id = $request->job_id;
        $cj->payrate = $request->hourly_payrate;
        $cj->ot_payrate = $request->ot_payrate;
        $cj->status = 1; // Applied
        $cj->created_by = auth()->user()->id;
        $cj->save();

        // Save Consultant Aging
        // Find days he is in the previous status
        $cid = $request->consultant_id;
        $previous = ConsultantAging::whereConsultant_id($cid)->whereActive(1)->first();
        if(is_null($previous)) {
            // Save new status
            $ca = new ConsultantAging;
            $ca->consultant_id = $cid;
            $ca->status = $request->status;
            $ca->save();
        } else {
            $prev_date = Carbon::parse($previous->created_at);
            $curr_date = Carbon::now();
            $diffDays = $prev_date->diffInDays($curr_date);
            
            // Update previous status days
            $previous->days = $diffDays;
            $previous->active = 0;
            $previous->update();

            // making all previous statuses to be inactive
            ConsultantAging::whereConsultant_id($cid)->update(['active'=>0]);

            $ca = new ConsultantAging;
            $ca->consultant_id = $cid;
            $ca->status = $request->status;
            if($request->status == 'joined') {
                $ca->job_id = $request->job_id;
                $ca->join_date = $request->job_start_date;
            }
            $ca->save();
        }

        DB::commit();

        $sts = "'joined'";
        $btn = 'Joined';
        $editbtn = '<a title="Edit Submission" href="/submissions/'.$newSubmission->id.'/edit"
                            class="btn btn-outline-info btn-circle-iconic btn34"> <i
                                class="material-icons">create</i></a>';

        return ['submission_id'=>$request->submission_id, 'btn'=>$btn, 'newId'=>$newSubmission->id, 'editbtn'=>$editbtn];
    }

    // Change submission status
    public function changeSubmissionStatus(Request $request)
    {
        // Replicate previous submission for history purpose
        $newSubmission = VendorSubmission::find($request->vendor_submission_id);
        $newSubmission = $newSubmission->replicate();
        $newSubmission->status = $request->status;
        $newSubmission->active = 1;
        $newSubmission->save();

        // Update previous submission
        $update = VendorSubmission::whereId($request->vendor_submission_id)->update(['active'=>0]);

        // Comment for consultant
        addConsultantComment($request->consultant_id, 'Submission status changed to '.ucwords($request->status));

        $vendor_statuses = config('custom.vendor_statuses');
        
        $sts = "'".$request->status."'";
        $sts1 = $vendor_statuses[$request->status];
        $btn = '<a href="#" onclick="changeStatus('.$sts.', '.$newSubmission->id.', '.$request->consultant_id.')"><u>'.$sts1.'</u></a>';
        $editbtn = '<a title="Edit Submission" href="/submissions/'.$newSubmission->id.'/edit"
                            class="btn btn-outline-info btn-circle-iconic btn34"> <i
                                class="material-icons">create</i></a>';

        return ['submission_id'=>$request->vendor_submission_id, 'btn'=>$btn, 'newId'=>$newSubmission->id, 'editbtn'=>$editbtn];
    }

    public function submissionJoinedList()
    {
        $list = VendorSubmission::with(['consultant', 'job', 'client', 'creater'])->whereCreated_by(auth()->user()->id)->whereStatus('joined')->get();
        $vendor_statuses = config('custom.vendor_statuses');

        $title = 'Joined Submissions List';

        return view('vendor-submissions.index', compact('list', 'vendor_statuses', 'title'));
    }
}
