<?php



namespace App\Http\Controllers\Settings;



use App\Http\Controllers\Controller;

use App\Http\Repository\UtilityRepository;

use App\Models\Settings\CmnBranch;

use App\Models\Settings\CmnBusinessHour;

use App\Models\Services\SchServices;

use Exception;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Validator;

use App\Http\Controllers\Api\UrlController;

use Illuminate\Support\Facades\Auth;

use App\Models\UserManagement\SecUserRole;

use App\Models\Website\SiteUrlShortenerMapping;

use Illuminate\Validation\Rule;

use Illuminate\Support\Arr;


class BranchController extends Controller

{

    public function __construct()

    {

        $this->middleware('auth');
    }



    public function branch()

    {
        $isMOGAdminOrSysAdmin = SecUserRole::where('sec_user_id', auth()->id())
                                ->where(function ($query) {
                                    $query->whereHas('role', function ($roleQuery) {
                                        $roleQuery->where('name', 'MOG Admin');
                                    })
                                    ->orWhereHas('user', function ($userQuery) {
                                        $userQuery->where('is_sys_adm', 1);
                                    });
                                })
                                ->exists();

        return view('settings.branch', compact('isMOGAdminOrSysAdmin'));
    }



    /**

     * Summary of saveCompany

     * Date: 22-Aug-2021

     * @param Request $data

     * @return \Illuminate\Http\JsonResponse

     */

    public function branchStore(Request $data)

    {

        try {

            $validator = Validator::make($data->all(), [

                'name' => ['required', 'string', Rule::unique('cmn_branches', 'name')],

                'short_name' => ['required', 'string', Rule::unique('cmn_branches', 'short_name')],

                'branch_code' => ['required', 'string', Rule::unique('cmn_branches', 'branch_code')],

                'name_slug' => ['required', 'string', Rule::unique('site_url_shortener_mappings', 'short_code')],

                'phone' => ['required', 'max:20'],

                'email' => ['required', 'email', 'unique:cmn_branches,email,' . $data['id']],

                'address' => ['required', 'string', 'max:300']

            ]);



            if (!$validator->fails()) {

                $data['created_by'] = auth()->id();

                $data['order'] = UtilityRepository::emptyOrNullToZero($data->order);
                
                $branch = CmnBranch::create([
                    'name' => $data['name'],
                    'short_name' => $data['short_name'],
                    'branch_code' => $data['branch_code'],
                    'name_slug' => $data['name_slug'],
                    'phone' => $data['phone'],
                    'email' => $data['email'],
                    'address' => $data['address'],
                    'status' => $data['status'],
                    'created_by' => $data['created_by'],
                    'order' => $data['order'],
                ]);

                for ($day = 0; $day < 7; $day++) {
                    CmnBusinessHour::updateOrCreate(
                        [
                            'cmn_branch_id' => $branch->id,
                            'day' => $day
                        ],
                        [
                            'start_time' => '10:00:00',
                            'end_time' => '22:00:00',
                            'is_off_day' => 0,
                            'created_by' => 1,
                        ]
                    );
                }
                
                $urlController = new UrlController();

                $services = SchServices::get();

                if ($data['shortenLink'] == 1) { 

                    $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$data['name_slug'], $data['name_slug'], 'branch', '', '');

                    foreach($services as $service) {
                        $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$data['name_slug'].'/service/'.$service['title_slug'], $data['name_slug'].'_'.$service['title_slug'], 'branch.service', '', '');
                    }

                }elseif ($data['shortenLink'] == 0) {

                    $urlController->removeShortenSlugUrl($data['name_slug']);

                    foreach($services as $service) {
                        $urlController->removeShortenSlugUrl($data['name_slug'].'_'.$service['title_slug']);
                    }

                }

                return $this->apiResponse(['status' => '1', 'data' => ''], 200);
            }

            return $this->apiResponse(['status' => '500', 'data' => $validator->errors()], 400);
        } catch (Exception $ex) {

            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }



    /**

     * Summary of updateCompany

     * Date: 22-Aug-2021

     * @param Request $data

     * @return \Illuminate\Http\JsonResponse

     */


    public function updateBranch(Request $data)

    {

        try {

            $validator = Validator::make($data->all(), [

                'name' => ['required', 'string', 'max:300'],

                'name_slug' => ['required', 'string', 'max:300'],

                'short_name' => ['required', 'string', 'max:20'],

                'branch_code' => ['required', 'string', 'unique:cmn_branches,branch_code,' . $data->id],

                'phone' => ['required', 'max:20'],

                'email' => ['required', 'email', 'unique:cmn_branches,email,' . $data['id']],

                'address' => ['required', 'string', 'max:300']

            ]);



            if (!$validator->fails()) {

                $data['updated_by'] = auth()->id();

                $data['order'] = UtilityRepository::emptyOrNullToZero($data->order);

                $urlController = new UrlController();

                $services = SchServices::get();

                if ($data['shortenLink'] == 1) {

                    $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$data['name_slug'], $data['name_slug'], 'branch', config('app.url').'/fireworks-appointment-booking/branch/'.$data['current_name_slug'], $data['current_name_slug']);

                    foreach($services as $service) {
                        $urlController->shortenSlugUrl(config('app.url').'/fireworks-appointment-booking/branch/'.$data['name_slug'].'/service/'.$service['title_slug'], $data['name_slug'].'_'.$service['title_slug'], 'branch.service', config('app.url').'/fireworks-appointment-booking/branch/'.$data['current_name_slug'].'/service/'.$service['title_slug'], $data['current_name_slug'].'_'.$service['title_slug']);
                    }

                }elseif ($data['shortenLink'] == 0) {

                    $urlController->removeShortenSlugUrl($data['name_slug']);

                    foreach($services as $service) {
                        $urlController->removeShortenSlugUrl($data['name_slug'].'_'.$service['title_slug']);
                    }

                }

                unset($data['shortenLink']);

                unset($data['current_name_slug']);
                
                CmnBranch::where('id', $data->id)->update($data->toArray());

                return $this->apiResponse(['status' => '1', 'data' => ''], 200);
            }

            return $this->apiResponse(['status' => '500', 'data' => $validator->errors()], 400);
        } catch (Exception $ex) {

            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }








    /**

     * Summary of delete Branch

     * Date: 8-Aug-2021

     * @param Request $data

     * @return \Illuminate\Http\JsonResponse

     */

    public function deleteBranch(Request $data)

    {
       
        try {

            $rtr = CmnBranch::where('id', $data->id)->delete();

            $urlController = new UrlController();

            $urlController->removeShortenSlugUrl($data->name_slug);

            $services = SchServices::get();
            
            foreach($services as $service) {
                $urlController->removeShortenSlugUrl($data['name_slug'].'_'.$service['title_slug']);
            }

            return $this->apiResponse(['status' => '1', 'data' => $rtr], 200);
        } catch (Exception $ex) {

            return $this->apiResponse(['status' => '501', 'data' => $ex], 400);
        }
    }







    public function branchGet($serviceId = null)

    {

        try {

            if (Auth::check() && (Auth::user()->is_sys_adm || Auth::user()->secUserRole->sec_role_id == 1 || Auth::user()->secUserRole->sec_role_id == 5)) {

                $data = CmnBranch::select(

                    'id',
    
                    'name',
    
                    'name_slug',
    
                    'short_name',
    
                    'branch_code',
    
                    'phone',
    
                    'email',
    
                    'address',
    
                    'order',
    
                    'status',
    
                    'created_by',
    
                    'updated_by'
    
                )->get();

                
            } else {
                $branchId = Auth::user()->branch->cmn_branch_id ?? null;

                if (!$branchId) {
                    return $this->apiResponse(['status' => '0', 'data' => 'You are not associated with any branch.'], 400);
                }
            
                $data = CmnBranch::select(
                    'id',
                    'name',
                    'name_slug',
                    'short_name',
                    'branch_code',
                    'phone',
                    'email',
                    'address',
                    'order',
                    'status',
                    'created_by',
                    'updated_by'
                )->where('id', $branchId)->get();
            
                if (!$data) {
                    return $this->apiResponse(['status' => '0', 'data' => 'Branch not found.'], 404);
                }
            
                return $this->apiResponse(['status' => '1', 'data' => $data], 200);
            }

            return $this->apiResponse(['status' => '1', 'data' => $data], 200);
        } catch (Exception $qx) {
            return $this->apiResponse(['status' => '403', 'data' => $qx], 400);
        }
    }





    public function getBranchList()

    {

        try {

            $data = CmnBranch::select('id', 'name', 'order')->get();

            return $this->apiResponse(['status' => '1', 'data' => $data], 200);
        } catch (Exception $qx) {

            return $this->apiResponse(['status' => '403', 'data' => $qx], 400);
        }
    }
}
