<?php

namespace App\Http\Controllers;

use UrlSigner;
use App\Models\Agreement;
use App\Models\Consultant;
use Illuminate\Http\Request;
use App\Models\AgreementPage;
use App\Models\AgreementReturn;
use Barryvdh\DomPDF\Facade as PDF;
use App\Models\ConsultantAgreement;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class AgreementController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = Agreement::latest()->get();
        $consultants = consultantSelect(auth()->user()->id);

        return view('agreements.index', compact('list', 'consultants'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('agreements.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // New Type saving created pdf
        \DB::beginTransaction();
        $agreement = new Agreement;
        $agreement->company_id = auth()->user()->company_id;
        $agreement->name = $request->name;
        if(isset($request->agreement)) {
            $file = $request->agreement;
            $ext = $file->getClientOriginalExtension();
            $filename = $request->name.'-'.time().'.'.$ext;
            $file->move(public_path('/storage/company_agreements'), $filename);
            $agreement->filename = $filename;
        }
        $agreement->user_id = auth()->user()->id;
        $agreement->save();
        \DB::commit();

        return redirect('/agreements')->with('success', 'PDF Saved Successfully!');

        // OLD Saving 
        /* Saving Agreement */
        $agreement = new Agreement;
        $agreement->company_id = auth()->user()->company_id;
        $agreement->name = $request->name;
        $agreement->header = $request->header;
        $agreement->footer = $request->footer;
        $agreement->save();

        /* Creating agreement content with pages */
        $agreement_content = '<html><head><style>@page { margin: 100px 25px; } header { position: fixed; top: -90px; left: 0px; right: 0px; text-align:center; } footer { position: fixed; bottom: -10px; left: 0px; right: 0px; height: 50px; text-align:center; } </style></head><body><header>'.$request->header.'</header><main>'; 
        $page_count = 0;
        foreach ($request->pages as $key => $page) {
            if($page != NULL){
                $ap = new AgreementPage;
                $ap->agreement_id = $agreement->id;
                $ap->content = $page;
                $ap->save();

                $page_count++;
                $agreement_content = $agreement_content.''.$page;
            }
        }

        $agreement_content = $agreement_content.'</main><footer>'.$request->footer.'</footer></body></html>';

        /* Updating agreement with number of page it contains */
        if($page_count != 0){
            $file = Agreement::find($agreement->id);
            $file->pages = $page_count;
            $file->save();
        }
    
        /* Creating Html File and PDF File on saving agreement and its content */
        if($agreement->id && $agreement_content) {
            $data = $agreement_content;
            $agreement_name = time().'.pdf';
            $dompdf = new PDF();
            $dompdf = \Barryvdh\DomPDF\Facade::loadHTML($data);
            // $dompdf->setPaper('A4');
            // $dompdf->stream();

            /*Storing Into Folder on File Save*/
            if(\Storage::disk('public')->put('company_agreements/'.$agreement_name, $dompdf->output())){
                /*Agreements Table Inserting if new one otherwise update*/
                $file = Agreement::find($agreement->id);
                $file->filename = $agreement_name;
                $file->save();
                /*Ends Here*/                 
            }
            /*Ends Here*/
        }
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Agreement  $agreement
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $agreement = Agreement::find($id);
        $pages = AgreementPage::where('agreement_id', $id)->get();

        return view('agreements.edit', compact('agreement', 'pages'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Agreement  $agreement
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        \DB::beginTransaction();

        $agreement = Agreement::find($id);
        $agreement->name = $request->name;
        $agreement->header = $request->header;
        $agreement->footer = $request->footer;
        $agreement->save();

        /*Deleting Previous pages*/
        AgreementPage::where('agreement_id', $id)->delete();

        $agreement_content = '<html><head><style>@page { margin: 100px 25px; } header { position: fixed; top: -90px; left: 0px; right: 0px; text-align:center; } footer { position: fixed; bottom: -10px; left: 0px; right: 0px; height: 50px; text-align:center; } </style></head><body><header>'.$request->header.'</header><main>'; 
        $page_count = 0;
        foreach ($request->pages as $key => $page) {
            if($page != NULL){
                $ap = new AgreementPage;
                $ap->agreement_id = $agreement->id;
                $ap->content = $page;
                $ap->save();

                $page_count++;
                $agreement_content = $agreement_content.''.$page;
            }
        }

        $agreement_content = $agreement_content.'</main><footer>'.$request->footer.'</footer></body></html>';
        if($page_count != 0){
            $file = Agreement::find($agreement->id);
            $file->pages = $page_count;
            $file->save();
        }

        if(isset($agreement->id) && isset($agreement_content)){
            $data = $agreement_content;
            $agreement_name = $request->consultantat_si_no.time().'.pdf';
            $dompdf = new PDF();
            $dompdf = \Barryvdh\DomPDF\Facade::loadHTML($data);
            $dompdf->setPaper('A4');
            $dompdf->stream();

            $last_file = Agreement::where('id', $id)->first();
            $last_file = 'public/storage/company_agreements/'.isset($last_file->agreement_file_name)?$last_file->agreement_file_name:'';

            if(file_exists($last_file)){
              unlink($last_file);
            }

            /*Storing Into Folder on File Save*/
            if(\Storage::disk('public')->put('company_agreements/'.$agreement_name, $dompdf->output())){
                /*Agreements Table Inserting if new one otherwise update*/
                $file = Agreement::find($agreement->id);
                $file->filename = $agreement_name;
                $file->save();
                /*Ends Here*/                 
            }
            /*Ends Here*/
        }

        \DB::commit();
        return redirect('/agreements');

    }

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

    /**
     * Send agreement to consultant
     */
    public function sendAgreement(Request $request)
    {
        $uid = auth()->user()->id;
        $uuids = userUserIds($uid);
        
        $consultants = consultantSelect($uid);
        $agreements = agreementSelect($uuids);

        // Consultant Agreements
        $agreement_list = ConsultantAgreement::with(['consultant', 'agreement'])->latest()->get();

        return view('agreements.send-agreement', compact('consultants', 'agreements', 'agreement_list'));
    }

    public function saveSendAgreement(Request $request)
    {
        /*Send a mail to Consultant.   */
        $password = Hash::make('secrete');  

        /*Creating Login Details For Student*/
        $agreement_data = new ConsultantAgreement();
        $agreement_data->consultant_id = $request->input('consultant_id');
        $agreement_data->agreement_id =  $request->agreement_id;
        $agreement_data->email = $request->input('email');
        $agreement_data->mobile = $request->input('mobile');
        $agreement_data->ssn =  $request->input('ssn');
        $agreement_data->payrate_type =  $request->payrate_type;
        $agreement_data->fixed_rate =  ($request->payrate_type=='fixed')?$request->fixed_rate:null;
        $agreement_data->percentage_rate =  ($request->payrate_type=='percentage')?$request->percentage_rate:null;
        $agreement_data->password = $password;
        $agreement_data->save(); 

        $from_filtr = explode('@', auth()->user()->email);
        if($from_filtr[1] != 'a10consultancy.com') {
            $from = $from_filtr[0].'@a10consultancy.com';
        }

        $dataLoad = ['cons_id' => $request->consultant_id, 'agg_id' => $request->agreement_id,'password'=>'secrete','username'=>$request->email, 'agreement_data_id'=>$agreement_data->id];

        Mail::send('agreements.expirylink.index', $dataLoad, function($message) use($from) {
            $message->from($from, ucfirst(auth()->user()->name));
            $message->to($_REQUEST['email'])->subject('Consultant Agreement!');
        });
        return redirect()->back()->with('success','Agreement Send Successfully');
    }

    /* Login */
    public function login()
    {
        $url = \Request::fullUrl();
        if(UrlSigner::validate($url)){
            return view('agreements.expirylink.login');
        }else{
            return 'Link Is Expired';
        }
    }

    /* Login Check */
    public function loginCheck(Request $request)
    {
        $this->validate($request,[
            'username' => 'required',
            'password' => 'required',
            'cand_id'  => 'required',
            'agreement_id' => 'required'
        ]);

       $match = ['email' => $request->username,'agreement_id' => $request->agreement_id, 'id'=>$request->login_id];
       
        $agreement_login_check = ConsultantAgreement::where($match)->first();
        if($agreement_login_check){
           $password = Hash::make($request->password);
           if (Hash::check('secrete',$password))
            {  
                if($agreement_login_check->status == 0){
                    $pages = AgreementPage::where('agreement_id', $request->agreement_id)->get();

                    $data['pages'] = $pages;
                    $data['cand_id'] = $request->cand_id;
                    $data['agreement_id'] = $request->agreement_id;
                    $data['login_id'] = $request->login_id;
                    $data['consultant'] = Consultant::whereId($request->cand_id)->first();
                    // return view('agreement.expirylink.agreement_view', $data);
                    return view('agreements.expirylink.view-latest', $data);
                }else{
                    return redirect()->back()->withError('You have already Submitted!');
                }
            }else{
                return redirect()->back()->withError('password','Password is not Match');
            }
        }else{
            return redirect()->back()->withError('username','UserName not Exists');
        }
    }

    /* Agreement returning */
    public function agreementReturn(Request $request)
    {
        // dd($request->all());
        \DB::beginTransaction();
        if($request->file('attachment_file')){
            $ext = $request->file('attachment_file')->getClientOriginalExtension();
            if($ext != 'pdf'){
                return redirect('/login')->with('Warning', 'Please Upload PDF File');
            }

            $f_name = quickRandom(16).time().'.'.$ext;
            $file = $request->file('attachment_file');
            if($file->move(public_path().'/storage/company_agreements/', $f_name)){

                $agR = new AgreementReturn;
                $agR->agreement_id = isset($request->agreement_id)?$request->agreement_id:'0';
                $agR->consultant_id = isset($request->cand_id)?$request->cand_id:'00';
                $agR->name = isset($request->name1)?$request->name1:'--';
                $agR->email = isset($request->email)?$request->email:'--'; 
                $agR->phone = isset($request->phone)?$request->phone:'00';
                $agR->ssn = isset($request->ssn)?$request->ssn:'00';
                $agR->file = isset($f_name)?$f_name:'--';
                $agR->login_ip = \Request::ip();
                $agR->save();

                if($agR){
                    $cr = ConsultantAgreement::where('id', $request->login_id)->first();
                    $cr->status = 1;
                    $cr->save();

                    return redirect('agreement_success_view');                    
                }
            }
        }
        \DB::commit(); 
    }

    public function successView(Request $request)
    {
        return view('agreements.expirylink.success_view');
    }

    public function agreementReturns()
    {
        $list = AgreementReturn::with(['consultant'])->get();

        return view('agreements.return-list', compact('list'));
    }
}
