<?php

namespace App\Http\Controllers\Accounts;

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

class AccountAddressesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:account-address-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        = AccountAddress::max('priority');
        $priority        = $priority != '' ? $priority : 0;
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select(
                                    'countries.code as country_code',
                                    'companies_addresses.country_id',
                                    'companies_addresses.state_id',
                                    'companies_addresses.city_id',
                                )
                                ->leftjoin('companies', 'companies.id', 'companies_addresses.company_id')
                                ->leftjoin('countries', 'countries.id', 'companies_addresses.country_id')
                                ->where('companies_addresses.company_id', $company_id)
                                ->orWhere('companies.is_default', '1')
                                ->first();

        return view('account-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(), [
            'account_id'    => 'required',
            'address_line1' => 'required',
            'country_id'    => 'required',
            'state_id'      => 'required',
            'post_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 = AccountAddress::create($data);

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

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

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

        return view('account-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       = AccountAddress::find($id);

        return view('account-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_line1' => 'required',
            'country_id'    => 'required',
            'state_id'      => 'required',
            'post_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 = AccountAddress::find($id);

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

        $account->update($data);

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

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

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

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

        $account->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 = AccountAddress::where(['id' => $request->id])->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Account 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  = AccountAddress::where(['is_default' => $request->status,'account_id'=> $request->account])->whereNull('deleted_at')->count();

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

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

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