<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CompanyAddress;
use App\Models\AddressType;
use App\Models\Country;

class CompanyAddressesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:company-addresses-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function createAddress($id)
    {
        $country       = Country::select(['id','name'])->where('status', '1')->get();
        $address_types = AddressType::select(['id','name','is_default'])->where('status', '1')->get();
        $priority      = CompanyAddress::max('priority');
        $priority      = $priority != '' ? $priority : 0;

        $company_address = \Session::get('company_data')['companies_addresses'];

        return view('company-addresses.create', compact('id','country','address_types','priority','company_address'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'company_id'    => 'required',
            'address_1' => 'required',
            'country_id'    => 'required',
            'state_id'      => 'required',
            'pin_code'      => 'required',
            'priority'      => 'required',
            'city_id'       => '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'
        ]);

        $default_check = CompanyAddress::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = "1";
        }

        $account = CompanyAddress::create($data);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $account_address = CompanyAddress::select([
                'companies_addresses.*',
                'countries.name as country',
                'states.name as state',
                'cities.name as city',
            ])
            ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
            ->leftjoin('states', 'states.id', 'companies_addresses.state_id')
            ->leftjoin('cities', 'cities.id', 'companies_addresses.city_id')
            ->find($id);

        if (!$account_address) {
            return redirect()->back()->with('error', 'Company Address id is invalid!');
        }

        return view('company-addresses.show', compact('account_address'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $country       = Country::select(['id','name'])->where('status', '1')->get();
        $address_types = AddressType::select(['id','name','is_default'])->where('status', '1')->get();
        $address       = CompanyAddress::find($id);

        return view('company-addresses.edit', compact('id','country','address_types','address'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'address_1'  => 'required',
            'country_id' => 'required',
            'state_id'   => 'required',
            'pin_code'   => 'required',
            'priority'   => 'required',
            'city_id'    => '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'
        ]);

        $account = CompanyAddress::find($id);

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

        $account->update($data);

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

        return redirect()->back()
            ->with('success','Company Address has been updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = CompanyAddress::find($request->id);

        if ($data->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'accounts';

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

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

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

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = CompanyAddress::where(['is_default' => $request->status,'company_id'=> $request->company])->whereNull('deleted_at')->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Company Address!'],
                    'data'    => []
                ]);
            }

            $Update = CompanyAddress::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Company Address default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
}
