<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\CsvImportTrait;
use App\Http\Controllers\Traits\MediaUploadingTrait;
use App\Http\Requests\MassDestroyAssetRequest;
use App\Http\Requests\StoreAssetRequest;
use App\Http\Requests\UpdateAssetRequest;
use App\Models\Asset;
use App\Models\CommissionData;
use App\Models\ContactCompany;
use App\Models\ContactContact;
use App\Models\FusionType;
use App\Models\UserSignature;
use App\Models\Product;
use App\Models\Team;
use App\Models\User;
use Barryvdh\DomPDF\PDF as DomPDFPDF;
use Illuminate\Support\Facades\URL;
use PDF;
use Gate;
use Illuminate\Http\Request;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Symfony\Component\HttpFoundation\Response;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Str;
use Creagia\LaravelSignPad\Concerns\RequiresSignature;
use Creagia\LaravelSignPad\Contracts\CanBeSigned;


class AssetController extends Controller
{
    use MediaUploadingTrait, CsvImportTrait,RequiresSignature;

    public function index(Request $request)
    {
        abort_if(Gate::denies('asset_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        if ($request->ajax()) {
            $query = Asset::with(['client', 'locations', 'air_compressor', 'airdryer', 'filter', 'eco_drain', 'air_receiver', 'commissioned_engineer', 'status', 'team'])->select(sprintf('%s.*', (new Asset)->table));
            $table = Datatables::of($query);

            $table->addColumn('placeholder', '&nbsp;');
            $table->addColumn('actions', '&nbsp;');

            $table->editColumn('actions', function ($row) {
                $viewGate      = 'asset_show';
                $editGate      = 'asset_edit';
                $deleteGate    = 'asset_delete';
                $crudRoutePart = 'assets';

                return view('partials.datatablesActions', compact(
                    'viewGate',
                    'editGate',
                    'deleteGate',
                    'crudRoutePart',
                    'row'
                ));
            });

            $table->editColumn('id', function ($row) {
                return $row->id ? $row->id : '';
            });
            $table->addColumn('client_company_name', function ($row) {
                return $row->client ? $row->client->company_name : '';
            });

            $table->editColumn('location', function ($row) {
                $labels = [];
                foreach ($row->locations as $location) {
                    $labels[] = sprintf('<span class="label label-info label-many">%s</span>', $location->location);
                }

                return implode(' ', $labels);
            });
            $table->addColumn('air_compressor_name', function ($row) {
                return $row->air_compressor ? $row->air_compressor->name : '';
            });

            $table->editColumn('air_compressor.model', function ($row) {
                return $row->air_compressor ? (is_string($row->air_compressor) ? $row->air_compressor : $row->air_compressor->model) : '';
            });
            $table->editColumn('air_compressor.part_no', function ($row) {
                return $row->air_compressor ? (is_string($row->air_compressor) ? $row->air_compressor : $row->air_compressor->part_no) : '';
            });
            $table->editColumn('air_compressor_serial_no', function ($row) {
                return $row->air_compressor_serial_no ? $row->air_compressor_serial_no : '';
            });
            $table->editColumn('air_compressor_part_no', function ($row) {
                return $row->air_compressor_part_no ? $row->air_compressor_part_no : '';
            });

            $table->addColumn('status_name', function ($row) {
                return $row->status ? $row->status->name : '';
            });

            $table->rawColumns(['actions', 'placeholder', 'client', 'location', 'air_compressor', 'status']);

            return $table->make(true);
        }

        $contact_companies = ContactCompany::get();
        $contact_contacts  = ContactContact::get();
        $products          = Product::get();
        $users             = User::get();
        $fusion_types      = FusionType::where('id','<=',8)->get();
        $teams             = Team::get();

        return view('admin.assets.index', compact('contact_companies', 'contact_contacts', 'products', 'users', 'fusion_types', 'teams'));
    }

    public function create()
    {
        abort_if(Gate::denies('asset_create'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $clients = ContactCompany::pluck('company_name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $locations = ContactContact::pluck('location', 'id');

        $air_compressors = Product::where('machine_type_id','=',1)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $airdryers = Product::whereIn('machine_type_id', [2, 3])->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $filters = Product::where('machine_type_id','=',6)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $eco_drains = Product::where('machine_type_id','=',7)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $air_receivers = Product::where('machine_type_id','=',array(4,5))->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $commissioned_engineers = User::whereHas(
            'roles', function($q){
                $q->where('title','Engineer');
            })
            ->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $statuses = FusionType::where('fusioncategory_id',9)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
        return view('admin.assets.create', compact('air_compressors', 'air_receivers', 'airdryers', 'clients', 'commissioned_engineers', 'eco_drains', 'filters', 'locations', 'statuses'));
    }

    public function store(StoreAssetRequest $request)
    {
        $asset = Asset::create($request->all());
        $asset->locations()->sync($request->input('locations', []));
        foreach ($request->input('asset_photos', []) as $file) {
            $asset->addMedia(storage_path('tmp/uploads/' . basename($file)))->toMediaCollection('asset_photos');
        }

        CommissionData::create(['commission_id'=>$asset->id,'commission_type_id'=>539,'commission_value'=>10,'commission_value_text_1'=>10,'commission_value_text_2'=>10,'commission_value_text_3'=>10]);


        if ($media = $request->input('ck-media', false)) {
            Media::whereIn('id', $media)->update(['model_id' => $asset->id]);
        }

        return redirect()->route('admin.assets.index');
    }

    public function edit(Asset $asset)
    {
        abort_if(Gate::denies('asset_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $clients = ContactCompany::pluck('company_name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $locations = ContactContact::pluck('location', 'id');

        $air_compressors = Product::where('machine_type_id','=',1)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $airdryers = Product::where('machine_type_id','=',2)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $filters = Product::where('machine_type_id','=',6)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $eco_drains = Product::where('machine_type_id','=',7)->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $air_receivers = Product::where('machine_type_id','=',array(3,4,5))->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $commissioned_engineers = User::whereHas(
            'roles', function($q){
                $q->where('title','Engineer');
            })
            ->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $statuses = FusionType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');

        $asset->load('client', 'locations', 'air_compressor', 'airdryer', 'filter', 'eco_drain', 'air_receiver', 'commissioned_engineer', 'status', 'team');

        $sampleurl=\URL::signedRoute('admin.assets.edit', compact('air_compressors', 'air_receivers', 'airdryers', 'asset', 'clients', 'commissioned_engineers', 'eco_drains', 'filters', 'locations', 'statuses'));
        //dd($sampleurl);

        return view('admin.assets.edit', compact('air_compressors', 'air_receivers', 'airdryers', 'asset', 'clients', 'commissioned_engineers', 'eco_drains', 'filters', 'locations', 'statuses'));
    }

    public function update(UpdateAssetRequest $request, Asset $asset)
    {

        //dd($request);
        $asset->update($request->all());
        // Make locations field non-mandatory by checking if it exists in the request
        if ($request->has('locations')) {
            $asset->locations()->sync($request->input('locations', []));
        }

        //Inserting the Signature Pad Sign
        //Laravel Upsert will not work for mysql, so use normal query
        CommissionData::updateOrCreate(
                        ['commission_id'=>$asset->id,'commission_type_id'=>608],
                        ['commission_value_text_3'=>$request->client_signature]);


                            //Inserting the Signature Pad Sign if not empty
                //Laravel Upsert will not work for mysql, so use normal query
                if(!empty($request->client_signature))    {
                    //Insert Signature
                    CommissionData::updateOrCreate(
                        ['commission_id'=>$asset->id,'commission_type_id'=>608],
                        ['commission_value_text_3'=>$request->client_signature]);

                        //Close Complaint
                        $asset::where('id',$asset->id)->update(['status_id'=>34]);
                }




        if (count($asset->asset_photos) > 0) {
            foreach ($asset->asset_photos as $media) {
                if (! in_array($media->file_name, $request->input('asset_photos', []))) {
                    $media->delete();
                }
            }
        }
        $media = $asset->asset_photos->pluck('file_name')->toArray();
        foreach ($request->input('asset_photos', []) as $file) {
            if (count($media) === 0 || ! in_array($file, $media)) {
                $asset->addMedia(storage_path('tmp/uploads/' . basename($file)))->toMediaCollection('asset_photos');
            }
        }

        return redirect()->route('admin.assets.index');
    }

    public function show(Asset $asset)
    {
        abort_if(Gate::denies('asset_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $asset->load('client', 'locations', 'air_compressor', 'airdryer', 'filter', 'eco_drain', 'air_receiver', 'commissioned_engineer', 'status', 'team', 'assetServiceComplaints', 'commissionCommissionDatas', 'assetAmcContracts');

        return view('admin.assets.show', compact('asset'));
    }

    public function destroy(Asset $asset)
    {
        abort_if(Gate::denies('asset_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $asset->delete();

        return back();
    }

    public function massDestroy(MassDestroyAssetRequest $request)
    {
        $assets = Asset::find(request('ids'));

        foreach ($assets as $asset) {
            $asset->delete();
        }

        return response(null, Response::HTTP_NO_CONTENT);
    }

    public function storeCKEditorImages(Request $request)
    {
        abort_if(Gate::denies('asset_create') && Gate::denies('asset_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $model         = new Asset();
        $model->id     = $request->input('crud_id', 0);
        $model->exists = true;
        $media         = $model->addMediaFromRequest('upload')->toMediaCollection('ck-media');

        return response()->json(['id' => $media->id, 'url' => $media->getUrl()], Response::HTTP_CREATED);
    }

    public function getAssetName(Request $request)
    {
        if($request->has('client_id')){
            //$asset_raw = Asset::where('client_id',$request->client_id)->get(['id','air_compressor_id']);

             $asset_raw = Asset::where('client_id', $request->client_id)->get(['id',
                                                                              'air_compressor_id','air_compressor_serial_no','air_compressor_part_no',
                                                                              'airdryer_id','airdryer_serial_no','air_dryer_part_no',
                                                                              'filter_id','filter_serial_no','filter_part_no',
                                                                              'eco_drain_id','eco_drain_serial_no','eco_drain_part_no',
                                                                              'air_receiver_id','air_receiver_serial_no','air_reciever_part_no']);

             // Collect all product IDs to fetch from products table
             $compressorIds = $asset_raw->pluck('air_compressor_id')->filter()->unique()->toArray();
             $dryerIds = $asset_raw->pluck('airdryer_id')->filter()->unique()->toArray();
             $filterIds = $asset_raw->pluck('filter_id')->filter()->unique()->toArray();
             $ecoDrainIds = $asset_raw->pluck('eco_drain_id')->filter()->unique()->toArray();
             $receiverIds = $asset_raw->pluck('air_receiver_id')->filter()->unique()->toArray();

             // Combine all IDs and fetch product names in a single query
             $allProductIds = array_merge($compressorIds, $dryerIds, $filterIds, $ecoDrainIds, $receiverIds);
             $products = Product::whereIn('id', $allProductIds)->pluck('name', 'id')->toArray();

             // Add product names to asset_raw collection
             $asset_raw = $asset_raw->map(function ($item) use ($products) {
                 $data = $item->toArray();

                 if (isset($data['air_compressor_id']) && isset($products[$data['air_compressor_id']])) {
                     $data['air_compressor_name'] = $products[$data['air_compressor_id']];
                 }

                 if (isset($data['airdryer_id']) && isset($products[$data['airdryer_id']])) {
                     $data['airdryer_name'] = $products[$data['airdryer_id']];
                 }

                 if (isset($data['filter_id']) && isset($products[$data['filter_id']])) {
                     $data['filter_name'] = $products[$data['filter_id']];
                 }

                 if (isset($data['eco_drain_id']) && isset($products[$data['eco_drain_id']])) {
                     $data['eco_drain_name'] = $products[$data['eco_drain_id']];
                 }

                 if (isset($data['air_receiver_id']) && isset($products[$data['air_receiver_id']])) {
                     $data['air_receiver_name'] = $products[$data['air_receiver_id']];
                 }

                 return $data;
             });


            // Remove null values from each asset in the collection
            $asset_raw = $asset_raw->map(function ($item) {
                return collect($item)
                    ->reject(function ($value) {
                        return is_null($value);
                    })
                    ->toArray();
            });

            //dd($asset_raw);
            $asset_values = [];

            foreach($asset_raw as $key => $value){
                if(isset($value['id'])) {
                    $asset_id = $value['id'];

                    // Air compressor data
                    if(isset($value['air_compressor_id']) || isset($value['air_compressor_serial_no']) || isset($value['air_compressor_part_no'])) {
                        $serial_no = $value['air_compressor_serial_no'] ?? '';
                        $part_no = $value['air_compressor_part_no'] ?? '';
                        $formatted_text = (isset($value['air_compressor_name']) ? $value['air_compressor_name'] : 'Unknown') . "-[Serial No]{$serial_no}-[Part No]{$part_no}";

                        if(!isset($value['air_compressor_id'])){
                            $value['asset_id_service_needed'] = $value['id'];
                            $value['air_compressor_id']=1;
                        }

                        $asset_values[] = [
                            'id' => $value['air_compressor_id'],
                            'asset_id_service_needed' =>$value['id'],
                            'asset' => "Air Compressor: {$formatted_text}"
                        ];
                    }

                    // Air dryer data
                    if(isset($value['airdryer_id']) || isset($value['airdryer_serial_no']) || isset($value['air_dryer_part_no'])) {
                        $serial_no = $value['airdryer_serial_no'] ?? '';
                        $part_no = $value['air_dryer_part_no'] ?? '';
                        $formatted_text = (isset($value['airdryer_name']) ? $value['airdryer_name'] : 'Unknown') . "-[Serial No]{$serial_no}-[Part No]{$part_no}";

                        if(!isset($value['airdryer_id'])){
                            $value['airdryer_id']=1;
                            $value['asset_id_service_needed'] = $value['id'];
                        }
                        $asset_values[] = [
                            'id' => $value['airdryer_id'],
                            'asset_id_service_needed' =>$value['id'],
                            'asset' => "Air Dryer: {$formatted_text}"
                        ];
                    }

                    // Filter data
                    if(isset($value['filter_id']) || isset($value['filter_serial_no']) || isset($value['filter_part_no'])) {
                        $serial_no = $value['filter_serial_no'] ?? '';
                        $part_no = $value['filter_part_no'] ?? '';
                        $formatted_text = (isset($value['filter_name']) ? $value['filter_name'] : 'Unknown') . "-[Serial No]{$serial_no}-[Part No]{$part_no}";

                        if(!isset($value['filter_id'])){
                            $value['filter_id']=1;
                            $value['asset_id_service_needed'] = $value['id'];
                        }
                        $asset_values[] = [
                            'id' => $value['filter_id'],
                            'asset_id_service_needed' =>$value['id'],
                            'asset' => "Filter: {$formatted_text}"
                        ];
                    }

                    // Eco drain data
                    if(isset($value['eco_drain_id']) || isset($value['eco_drain_serial_no']) || isset($value['eco_drain_part_no'])) {
                        $serial_no = $value['eco_drain_serial_no'] ?? '';
                        $part_no = $value['eco_drain_part_no'] ?? '';
                        $formatted_text = (isset($value['eco_drain_name']) ? $value['eco_drain_name'] : 'Unknown') . "-[Serial No]{$serial_no}-[Part No]{$part_no}";
                        if(!isset($value['eco_drain_id'])){
                            $value['eco_drain_id']=1;
                            $value['asset_id_service_needed'] = $value['id'];
                        }
                        $asset_values[] = [
                            'id' => $value['eco_drain_id'],
                            'asset_id_service_needed' =>$value['id'],
                            'asset' => "Eco Drain: {$formatted_text}"
                        ];
                    }

                    // Air receiver data
                    if(isset($value['air_receiver_id']) || isset($value['air_receiver_serial_no']) || isset($value['air_reciever_part_no'])) {
                        $serial_no = $value['air_receiver_serial_no'] ?? '';
                        $part_no = $value['air_reciever_part_no'] ?? '';
                        $formatted_text = (isset($value['air_receiver_name']) ? $value['air_receiver_name'] : 'Unknown') . "-[Serial No]{$serial_no}-[Part No]{$part_no}";

                        if(!isset($value['air_receiver_id'])){
                            $value['air_receiver_id']=1;
                            $value['asset_id_service_needed'] = $value['id'];
                        }
                        $asset_values[] = [
                            'id' => $value['air_receiver_id'],
                            'asset_id_service_needed' =>$value['id'],
                            'asset' => "Air Receiver: {$formatted_text}"
                        ];
                    }

                    // If no specific components were found, add a generic entry

                }
            }
            return $asset_values;
        }
    }


    public function createcommissionpdf(Request $request, Asset $asset)
    {
        //dd($request->Assetid);
        $asset=$asset->find($request->Assetid)->load('client', 'locations', 'air_compressor', 'airdryer', 'filter', 'eco_drain', 'air_receiver', 'commissioned_engineer', 'status', 'team', 'assetServiceComplaints', 'commissionCommissionDatas', 'assetAmcContracts');
        $user_sign=UserSignature::where('user_id',$asset->commissioned_engineer_id)->pluck('temp');

        $user_sign=UserSignature::where('user_id',$asset->commissioned_engineer_id)->pluck('temp');
        $_dompdf_warnings = array();
        $_dompdf_show_warnings = true;
        //view('admin.hacs.Subsystems.tags.pdf', compact('hac'));
        PDF::setOptions(['debugCss'=> true,'debugPng'=> true,'defaultFont' => 'Open Sans','isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true ,'chroot' => public_path()]);

        $pdf = PDF::loadView('admin.assets.createcommissionpdf',compact('user_sign','asset'))->setOptions(['defaultFont' => 'sans-serif']);

        // set filename
        $filename= 'Commissioning_'. $asset->id . '_' . $asset->client->company_name . '_' . date('d-m-Y-h-s');

        //To Download PDF on Browser, comment it if you want to check the PDF rendering on Browser
        return $pdf->download($filename.'.pdf');

        //To check the redendring of the PDF on Browser
        return view('admin.assets.createcommissionpdf', compact('user_sign','asset'));
    }


    public function createsignedurl(Request $request,Asset $asset)
    {
        if (!$request->hasValidSignature()) {
            abort(401);
        }

        return URL::signedRoute('edit', ['asset' => $asset->id]);

    }
}
/*

//Create PDF

    public function createcomplaintpdf(Request $request, ServiceComplaint $serviceComplaint)
    {

        abort_if(Gate::denies('service_complaint_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        //$cid = $request->Complaintid;


        $serviceComplaint=$serviceComplaint->find($request->Complaintid)->load('client', 'location', 'asset', 'service_type', 'visit_type', 'status', 'enginner_assigned', 'supervisor_assigned', 'team', 'complaintChecklistReports');

        $user_sign=UserSignature::where('user_id',$serviceComplaint->enginner_assigned->id)->pluck('temp');
        $_dompdf_warnings = array();
        $_dompdf_show_warnings = true;
        //view('admin.hacs.Subsystems.tags.pdf', compact('hac'));
        PDF::setOptions(['debugCss'=> true,'debugPng'=> true,'defaultFont' => 'Open Sans','isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true ,'chroot' => public_path()]);

        $pdf = PDF::loadView('admin.serviceComplaints.createcomplaintpdf',compact('user_sign','serviceComplaint'))->setOptions(['defaultFont' => 'sans-serif']);

        // set filename
        $filename= $serviceComplaint->id . '_' . $serviceComplaint->client->company_name . '_' . date('d-m-Y-h-s');

        //To Download PDF on Browser, comment it if you want to check the PDF rendering on Browser
        return $pdf->download($filename.'.pdf');

        //To check the redendring of the PDF on Browser


        return view('admin.serviceComplaints.createcomplaintpdf', compact('user_sign','serviceComplaint'));
    }





-----------
`id`,
`air_compressor_id`,
`air_compressor_serial_no`,
`air_compressor_part_no`,

`airdryer_id`,
`airdryer_serial_no`,
`air_dryer_part_no`,

`filter_id`,
`filter_serial_no`,
`filter_part_no`,

`eco_drain_id`,
`eco_drain_serial_no`,
`eco_drain_part_no`,

`air_receiver_id`
`air_receiver_serial_no`,
`air_reciever_part_no`,

 )
*/
