<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\CompanyAddress;
use App\Models\CompanyImage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CompanyImagesController extends Controller
{
    public function index(Request $request)
    {
        $CompanyImage = CompanyImage::select([
            'id',
            'company_id',
            'image_url',
            'image_type',
            'status',
            'priority',
            'height width',
            'top-margin ',
            'bottom-margin ',
            'left-margin  ',
            'right-margin',
            'top-padding ',
            'bottom-padding ',
            'left-padding ',
            'right-padding',
            'alignment',
            'height',
            'width'
        ]);
            // ->leftjoin('countries', 'countries.id', 'companies_license_type.country_id');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $CompanyImage = $CompanyImage->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('image_url', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('company-images.table', compact('CompanyImage'));
        }
        else
        {
            $CompanyImage = $CompanyImage->paginate(10);

            return view('company-images.index',compact('CompanyImage'));
        }
    }

    public function createImages($id)
    {
        $countries       = \DB::table('countries')->select(['id','name'])->where('status', '1')->get();
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select([
                                'companies_addresses.country_id',
                            ])
                            ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
                            ->where('company_id', $company_id)
                            ->orWhere('companies.is_default', '1')
                            ->first();

        $country_id = $company_address->country_id ?? '';
        $priority   = CompanyImage::max('priority');
        $priority   = $priority != '' ? $priority : 0;

        return view('company-images.create', compact('countries','country_id','priority','id'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'image_url'  => 'required|image',
            'image_type' => 'required',
            'height'     => 'required',
            'width'      => 'required',
            'alignment'  => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $data                  = $request->all();
        $data['company_id']    = \Auth::user()->company_id ?? '';
        $data['page_position'] = 'Header';
        $data['view_priority'] = 'Top';

        $data = $request->except([
            '_token',
            '_method',
            'image_url'
        ]);

        //image
        if ($request->hasFile('image_url')) {
            $path     = "company-images";
            $response = uploadImage($path,$request->image_url);

            if ($response['status'] == true) {
                $data['image_url'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $data['top_margin']     = $request->filled('top_margin') ? $request->top_margin : 0;
        $data['bottom_margin']  = $request->filled('bottom_margin') ? $request->bottom_margin : 0;
        $data['left_margin']    = $request->filled('left_margin') ? $request->left_margin : 0;
        $data['right_margin']   = $request->filled('right_margin') ? $request->right_margin : 0;
        $data['top_padding']    = $request->filled('top_padding') ? $request->top_padding : 0;
        $data['bottom_padding'] = $request->filled('bottom_padding') ? $request->bottom_padding : 0;
        $data['left_padding']   = $request->filled('left_padding') ? $request->bottom_padding : 0;
        $data['right_padding']  = $request->filled('right_padding') ? $request->bottom_padding : 0;

        CompanyImage::insert($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Company Image created successfully',
            ]);
        }

        return redirect('license')->with('success','Company Image created successfully.');
    }

    public function edit($id,Request $request)
    {
        $data     = CompanyImage::find($id);
        $CompanyData = Company::select(['id','name'])->latest('id')->get();

        $countries = DB::table('countries')->select(['id','name'])->where('status', '1')->get();

        return view('company-images.edit',compact('countries','data','id'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            // 'image_url'  => 'required|image',
            'image_type' => 'required',
            'height'     => 'required',
            'width'      => 'required',
            'alignment'  => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'image_url',
        ]);

        $type = CompanyImage::find($id);

        if (!$type) {
            return redirect()->back()
                ->with('error','Company License not found!');
        }

        if ($request->hasFile('image_url')) {
            $path               = "company-documents";
            $response = uploadImage($path,$request->image_url);

            if ($response['status'] == true) {
                $data['image_url'] = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }
        }

        $data['top_margin']     = $request->filled('top_margin') ? $request->top_margin : 0;
        $data['bottom_margin']  = $request->filled('bottom_margin') ? $request->bottom_margin : 0;
        $data['left_margin']    = $request->filled('left_margin') ? $request->left_margin : 0;
        $data['right_margin']   = $request->filled('right_margin') ? $request->right_margin : 0;
        $data['top_padding']    = $request->filled('top_padding') ? $request->top_padding : 0;
        $data['bottom_padding'] = $request->filled('bottom_padding') ? $request->bottom_padding : 0;
        $data['left_padding']   = $request->filled('left_padding') ? $request->bottom_padding : 0;
        $data['right_padding']  = $request->filled('right_padding') ? $request->bottom_padding : 0;

        $type->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Company Image has been updated successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Company Image has been updated successfully');
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax())
        {
            $data   = array('status' => $request->status );
            $Update = CompanyImage::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Comapny Images status successfully change'],
                    'data'    => [
                        'redirect' =>'/license/',
                        'reload'   =>true,
                    ]
                ]);
            }
            else{
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function destroy(Request $request)
    {
       $about = CompanyImage::find($request->id);
       $about->delete();
       $Redirect = 'license';

       return response()->json([
           'success' => true,
           'message' => ['Deleted successfully'],
           'data'    => [
              'redirect' => $Redirect,
           ]
       ]);
    }
}
