<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\OBF;
use App\Models\Product;
use Illuminate\Http\Request;
use Validator, DB;

class ObfArrovalController extends Controller
{
    /** construct */
        public function __construct(){
            $this->middleware('permission:obf_approval-create', ['only' => ['create']]);
            $this->middleware('permission:obf_approval-edit', ['only' => ['edit']]);
            $this->middleware('permission:obf_approval-view', ['only' => ['view']]);
            $this->middleware('permission:obf_approval-delete', ['only' => ['delete']]);
        }
    /** construct */
    /** index */
        public function index(Request $request){
            if(auth()->user()->can('obf_approval-view')){
                $data = OBF::select(
                    'obf.id',
                    'obf.temporary_id',
                    'obf.customer_name',
                    'obf.booking_date',
                    'obf.status',
                    'obf.approval_status',
                    'products.name as product_name',
                    'products.veriant'
                )
                ->leftJoin('products', 'obf.product_id', '=', 'products.id')
                ->whereIn('obf.status', ['pending','account_accepted','deal_generated','completed'])
                ->whereIn('obf.approval_status', [
                    'pending',
                    'obf_tl_accepted',
                    'obf_sm_accepted',
                    'obf_gm_accepted',
                    'obf_accountant_accepted',
                    'obf_tl_rejected',
                    'obf_sm_rejected',
                    'obf_gm_rejected',
                    'obf_accountant_rejected'
                ]);

                if(!empty(auth()->user()->branch)){
                    $data = $data->whereRaw('FIND_IN_SET(obf.branch_id ,"'.auth()->user()->branch.'")');
                }

                $roleHierarchy = [
                    'Team leader' => ['obf_tl_accepted', 'obf_sm_accepted', 'obf_gm_accepted'],
                    'Sales Manager' => ['obf_sm_accepted', 'obf_gm_accepted'],
                    'General Manager - Sales' => ['obf_gm_accepted'],
                ];

                $currentUser = auth()->user();
                foreach ($roleHierarchy as $role => $statuses) {
                    if ($currentUser->hasRole($role)) {
                        $data = $data->whereNotIn('obf.approval_status', $statuses);
                        break;
                    }
                }

                $data = $data->orderBy('obf.id', 'desc')->get();

                if(sizeof($data)){
                    return response()->json(['status' => 200 ,'message' => 'Data Found.' , 'Data' => $data]);
                }else{
                    return response()->json(['status' => 404 ,'message' => 'No Data Found.']);
                }
            }else{
                return response()->json(['status' => 401, 'message' => 'Not Authorized.']);
            }
        }
    /** index */

    /** view */
        public function view(Request $request){
            if(auth()->user()->can('obf_approval-view')){
                $path = URL('/uploads/kyc').'/';
                $data = OBF::select(
                    'obf.id',
                    'obf.temporary_id',
                    'obf.booking_date',
                    'obf.customer_name',
                    'obf.customer_type',
                    'obf.company_name',
                    'obf.gst',
                    'obf.address',
                    'obf.registration',
                    'obf.email',
                    'obf.pan_number',
                    'obf.adhar_number',
                    'obf.licance_number',
                    'obf.contact_number',
                    'obf.dob',
                    'obf.nominee_name',
                    'obf.nominee_reletion',
                    'obf.nominee_age',
                    'obf.occupation',
                    'obf.exterior_color',
                    'obf.interior_color',
                    'obf.ex_showroom_price',
                    'obf.on_road_price',
                    'obf.on_road_price_word',
                    'obf.booking_amount',
                    'obf.mode_of_payment',
                    'obf.status',
                    'obf.approval_status',
                    'obf.reason',
                    'branches.name AS branch_name',
                    'products.name AS product_name',
                    'products.veriant',
                    DB::raw("CONCAT(users.first_name,' ',users.last_name) AS sales_person_name"),
                    DB::raw("CASE WHEN pan_image != '' THEN CONCAT('".$path."', pan_image) ELSE CONCAT('".$path."', 'default.jpg') END as pan_image"),
                    DB::raw("CASE WHEN adhar_image != '' THEN CONCAT('".$path."', adhar_image) ELSE CONCAT('".$path."', 'default.jpg') END as adhar_image"),
                    DB::raw("CASE WHEN licance_image != '' THEN CONCAT('".$path."', licance_image) ELSE CONCAT('".$path."', 'default.jpg') END as licance_image")
                )
                ->leftJoin('users', 'obf.sales_person_id', '=', 'users.id')
                ->leftJoin('branches', 'obf.branch_id', '=', 'branches.id')
                ->leftJoin('products', 'obf.product_id', '=', 'products.id')
                ->where(['obf.id' => $request->id])
                ->first();
                
                if($data)
                    return response()->json(['status' => 200, 'message' => 'Data found', 'data' => $data]);
                else
                    return response()->json(['status' => 404, 'message' => 'No data found']);
            }else{
                return response()->json(['status' => 401, 'message' => 'Not Authorized.']);
            }
        }
    /** view */

    /** change-status */
        public function change_status(Request $request){
            if(auth()->user()->can('obf_approval-delete')){
                $rules = [
                    'id' => 'required',
                    'status' => 'required|in:obf_tl_accepted,obf_tl_rejected,obf_sm_accepted,obf_sm_rejected,obf_gm_accepted,obf_gm_rejected,obf_accountant_accepted,obf_accountant_rejected'
                ];

                $validator = Validator::make($request->all(), $rules);

                if($validator->fails())
                    return response()->json(['status' => 422, 'message' => $validator->errors()]);

                $data = OBF::where(['id' => $request->id])->first();

                if(!empty($data)){
                    $assignFlag = auth()->user()->flag ?? null;
                    $requestedStatus = $request->status;
                    $currentStatus = $data->approval_status ?? 'pending';

                    if($data->status === 'deal_generated' && $assignFlag !== "4"){
                        return response()->json(['status' => 422, 'message' => 'Deal Generated - You Can Not Edit this OBF']);
                    }

                    $allowedStatuses = [];
                    if($assignFlag === "1"){
                        if(!in_array($currentStatus, ['obf_sm_accepted', 'obf_sm_rejected','obf_gm_accepted', 'obf_gm_rejected','obf_accountant_accepted','obf_accountant_rejected'])){
                            $allowedStatuses = ['obf_tl_accepted', 'obf_tl_rejected'];
                        }
                    }else if($assignFlag === "2"){
                        if(!in_array($currentStatus, ['obf_gm_accepted', 'obf_gm_rejected','obf_accountant_accepted','obf_accountant_rejected'])){
                            $allowedStatuses = ['obf_sm_accepted', 'obf_sm_rejected'];
                        }
                    }else if($assignFlag === "3"){
                        if(!in_array($currentStatus, ['obf_accountant_accepted','obf_accountant_rejected'])){
                            $allowedStatuses = ['obf_gm_accepted', 'obf_gm_rejected'];
                        }
                    }else if($assignFlag === "4"){
                        $allowedStatuses = ['obf_accountant_accepted', 'obf_accountant_rejected'];
                    }

                    if(empty($allowedStatuses) || !in_array($requestedStatus, $allowedStatuses)){
                        return response()->json(['status' => 403, 'message' => 'This approval action is not allowed for your current role or stage.']);
                    }

                    if(str_contains($requestedStatus, '_rejected') && empty($request->reason)){
                        return response()->json(['status' => 422, 'message' => ['reason' => ['The reason field is required for rejection.']]]);
                    }

                    $update = OBF::where(['id' => $request->id])->update([
                        'approval_status' => $requestedStatus,
                        'reason' => $request->reason,
                        'updated_at' => date('Y-m-d H:i:s'),
                        'updated_by' => auth('sanctum')->user()->id
                    ]);
                    
                    if($update){
                        return response()->json(['status' => 200 ,'message' => 'Record status change successfully']);
                    }else{
                        return response()->json(['status' => 201, 'message' => 'Faild to update status']);
                    }
                }else{
                    return response()->json(['status' => 201, 'message' => 'Somthing went wrong !']);
                }
            }else{return response()->json(['status' => 401, 'message' => 'Not Authorized.']);}
        }
    /** change-status */
}
