<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Website\Branch;
use App\Models\Website\BranchType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BranchesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:branch-list|branch-create|branch-edit|branch-delete', ['only' => ['index','store','list']]);
    }

    public function index(Request $request)
    {
        $branch = Branch::with('getBranchType')->select([
            'id',
            'title',
            'branch_type_id',
            'phone',
            'priority',
            'status'
        ]);

        $sort_by        = $request->get('sortby') ?? 10;
        $sort_type      = $request->get('sorttype');
        $query          = $request->get('query');
        if (!empty($query) && !empty($sort_by) && $query != " ") {

            $branch->where('title', 'like', '%' . $query . '%');
        }
        $branches = $branch->orderBy('id', 'desc')->paginate($sort_by);
        if ($request->ajax()) {
            return view('website-setting.branches.table', compact('branches'));
        } else {
            return view('website-setting.branches.index', compact('branches'));
        }
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $types = BranchType::where('status', '1')->get();

        $priority    = Branch::max('priority');
        $priority    = $priority != '' ? $priority : 0;
        return view('website-setting.branches.create', compact('priority', 'types'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        if ($request->isMethod('post')) {
            // return $request;
            $validator =  Validator::make($request->all(), [
                'title'          => 'required',
                'phone'          =>  'required',
                'email'          =>  'required',
                'branch_type_id' =>  'required'
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
            } else {

                if ($request->hasFile('cover_image')) {
                    $url        = \Str::slug($request->title);
                    $path       = "upload/branch/" . $url . '/' . date('Y') . '/' . date('m');
                    $response = uploadImage($path, $request->cover_image);

                    if ($response['status'] == true) {
                        $image = $response['file_name'];
                    } else {
                        return response()->json([
                            'success' => false,
                            'message' => $response['message'],
                            'data'    => []
                        ]);
                    }
                } else {
                    $image = '';
                }

                $Brach = Branch::create([
                    'title'                 => $request->title,
                    'phone'                 => $request->phone,
                    'branch_type_id'        => $request->branch_type_id ?? 1,
                    'company_id'            => auth()->user()->company_id,
                    'address'               => $request->address,
                    'email'                 => $request->email,
                    'google_map'            => $request->google_map,
                    'cover_image'           => $image,
                    'priority'              => $request->priority,
                ]);
                //
                $Redirect = '/branches/';
                return response()->json([
                    'success' => true,
                    'message' => ['Branch successfully created'],
                    'data' => $Brach
                ]);
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Request $request)
    {
        $branch = Branch::where(['id' => $id])->first();
        $types = BranchType::where('status', '1')->get();

        return view('website-setting.branches.edit')->with([
            'branch' => $branch,
            'types' => $types,
        ]);
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id, Request $request)
    {
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id, Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'title'          =>  'required',
            'phone'          =>  'required',
            'email'          =>  'required',
            'branch_type_id' =>  'required'
        ]);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
        } else {
            $branch = Branch::find($id);
            $url        = \Str::slug($request->title);
            if ($request->hasFile('cover_image')) {
                $path       = "upload/branch/" . $url . '/' . date('Y') . '/' . date('m');
                $response = uploadImage($path, $request->cover_image);

                if ($response['status'] == true) {
                    $image = $response['file_name'];
                } else {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
            } else {
                $image = $branch->cover_image;
            }

            $data = array(
                'title'                 => $request->title,
                'phone'                 => $request->phone,
                'branch_type_id'        => $request->branch_type_id ?? 1,
                'company_id'            => auth()->user()->company_id,
                'address'               => $request->address,
                'email'                 => $request->email,
                'google_map'            => $request->google_map,
                'cover_image'           => $image,
                'priority'              => $request->priority,
            );
            $branch->update($data);
            $data = Branch::find($id);
            //
            $Redirect = '';
            return response()->json([
                'success' => true,
                'message' => ['Branch successfully Update'],
                'data' => $data
            ]);
        }
    }




    /**
     * change Blog status.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function changestatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = Branch::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Status successfully change'],
                    'data' => [
                        'redirect' => '/branches/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $Delete = Branch::where(['id' => $request->id])->delete();
        $Redirect = '/branches';
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
}
