<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Currency;
use Illuminate\Support\Facades\Validator;
use App\Models\Employer;
use App\Models\Admin;
use App\Models\Staff;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;


class CurrenciesController extends Controller
{
    public function currencyListing(Request $request){
        $currentUser = Auth::user()->id;
        
        $staffDetail = Staff::find($currentUser);
        
        if(!empty($staffDetail)){
            
            $adminData = $staffDetail;
                
                $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
            
                    global $subadminAccess;
                    $accessControlArray = $subadminAccess;
            
                    if (!is_array($accessControlArray)) {
                        return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                    }
            
                    $accessArray = [];
                    foreach ($accessControlArray as $key => $ac) {
                        $accessArray[$key] = $ac; // Start with the original sub-array
            
                        // Override with $accessData if available
                        if (isset($accessData[$key])) {
                            foreach ($accessData[$key] as $accessKey => $accessValue) {
                                $accessArray[$key][$accessKey] = $accessValue;
                            }
                        }
                    }
                
                
                if($accessArray['7']['Module'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
        }
        
        
        $data = array();
        
        $currencies = '';
        
        if($request->user_type == 'employer'){
            $currencies = Currency::where('employer_id', $currentUser)->orderBy('id', 'Desc')->get();
        } else{
            
            $employerId = Staff::where('id', $currentUser)->value('employer_id');
            
            $currencies = Currency::where('employer_id', $employerId)->orWhere('staff_id', $currentUser)->get();
            
        }
        
        
        $currencyArray = array();
        foreach($currencies as $key => $currency) {
            $currencyArray[$key]['id'] = $currency->id;
            $currencyArray[$key]['slug'] = $currency->slug;
            $currencyArray[$key]['name'] = $currency->name;
            $currencyArray[$key]['code'] = $currency->code;
            $currencyArray[$key]['symbol'] = $currency->symbol;
            $currencyArray[$key]['symbol_place'] = $currency->symbol_place;
            $currencyArray[$key]['is_default'] = $currency->is_default;
            $currencyArray[$key]['status'] = $currency->status;
            $currencyArray[$key]['user_type'] = $currency->user_type;
        }
        
        $data['currency'] = $currencyArray;
        
        return Response(['response' => $data, 'message' => 'success', 'status' => 200], 200);
    }
    
    // public function currencyAdd(Request $request){
        
    //     $currentUser = Auth::user()->id;
        
    //     $validator = Validator::make($request->all(), [
    //         'name' => 'required|unique:currencies,name',
    //         'code' => 'required',
    //         'symbol' => 'required',
    //     ]);
        
    //     if ($validator->fails()) {
    //         $msg = $this->validatersErrorString($validator->errors());
    //         return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
    //     } else{
    //         $slug = Str::slug($request->name);
    //         Currency::create([
    //             'employer_id' => $currentUser,
    //             'name' => $request->name,
    //             'code' => $request->code,
    //             'symbol' => $request->symbol,
    //             'symbol_place' =>'before',
    //             'is_default' => '0',
    //             // 'slug' => $this->createSlug($request->name,'currencies'),
    //             'slug' => $slug,
    //             'status' => 1,
    //         ]);

    //         return Response(['response' => '' , 'message' => 'Currency Added Successfully' , 'status' => 200],200);
    //     }
    // }
    
    
    public function currencyAdd(Request $request)
    {
        $currentUser = Auth::user()->id;
        
        $staffDetail = Staff::find($currentUser);
        
            if(!empty($staffDetail)){
                
                $adminData = $staffDetail;
                    
                    $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
                        global $subadminAccess;
                        $accessControlArray = $subadminAccess;
                
                        if (!is_array($accessControlArray)) {
                            return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
                        }
                
                        $accessArray = [];
                        foreach ($accessControlArray as $key => $ac) {
                            $accessArray[$key] = $ac; // Start with the original sub-array
                
                            // Override with $accessData if available
                            if (isset($accessData[$key])) {
                                foreach ($accessData[$key] as $accessKey => $accessValue) {
                                    $accessArray[$key][$accessKey] = $accessValue;
                                }
                            }
                        }
                    
                    
                if($accessArray['7']['Add'] == 0){
                    return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
                }
            }
            
        if(!empty($request->all())){
            $validator = Validator::make($request->all(), [
                'name' => [
                    'required',
                    Rule::unique('currencies', 'name')->where(function ($query) use ($currentUser) {
                        return $query->where('employer_id', $currentUser);
                    }),
                ],
                'code' => 'required',
                'symbol' => 'required',
            ]);
            
                
        
            if ($validator->fails()) {
                $msg = $this->validatersErrorString($validator->errors());
                return Response(['response' => "", 'message' => $msg, 'status' => 500], 200);
            } else {
                $slug = Str::slug($request->name);
                
                if($request->user_type == 'employer'){
                    
                    Currency::create([
                        'employer_id' => $currentUser,
                        'name' => $request->name,
                        'code' => $request->code,
                        'symbol' => $request->symbol,
                        'symbol_place' => 'before',
                        'is_default' => '0',
                        'slug' => $slug,
                        'status' => 1,
                        'staff_id' => '',
                        'user_type' => $request->user_type,
                    ]);
                    
                } else{
                    
                    $employerId = Staff::where('id', $currentUser)->value('employer_id');
                    
                    Currency::create([
                        'employer_id' => $employerId,
                        'name' => $request->name,
                        'code' => $request->code,
                        'symbol' => $request->symbol,
                        'symbol_place' => 'before',
                        'is_default' => '0',
                        'slug' => $slug,
                        'status' => 1,
                        'staff_id' => $currentUser,
                        'user_type' => $request->user_type
                    ]);
                    
                }
        
                return Response(['response' => '', 'message' => 'Currency Added Successfully', 'status' => 200], 200);
            }
        }
    
        // Validation with unique check for employer-specific currency names
        
    }

    
    public function currency_changeStatus($id) {
        $currentStatus = Currency::where('id', $id)->value('status');
        $currencyData = Currency::where('id', $id)->first();

        if($id != ''){
            if($currencyData->is_default == "1"){
                return Response(['response' => '', 'message' => 'Default currency status cannot be changed', 'status' => 500], 200);
            }
            if($currentStatus == 1){
                Currency::where('id', $id)->update([
                    'status' => 0,
                ]);
            }else{
                Currency::where('id', $id)->update([
                    'status' => 1,
                ]);
            }
            
            return Response(['response' => 'Activated Successfully', 'message' => 'Activated Successfully', 'status' => 200],200);
        }
        return Response(['response' => 'Id not found', 'message' => 'Id not found', 'status' => 500], 200);
    }
    
    
    public function currency_Delete($id){
        $currencyData = Currency::where('id', $id)->first();
        
        if(!empty($currencyData)){
            if($currencyData->is_default == "1"){
                return Response(['response' => '', 'message' => 'Default currency cannot be deleted', 'status' => 500], 200);
            }
            Currency::where('id', $id)->delete();
            
            return Response(['response' => 'Currency Deteled Successfully', 'message' => 'success', 'status' => 200], 200);
        }else{
            return Response(['response' => 'No record deleted', 'message' => 'No record deleted', 'status' => 500], 200);
        }
    }
    
    public function currency_Edit(Request $request,$id){
        $currencyData = Currency::where('id', $id)->first();
        
        $userId = Auth::user()->id;
        
        $staffDetail = Staff::find($userId);
        
        if(!empty($staffDetail)){
            $adminData = $staffDetail;
                
            $accessData = isset($adminData->roles) ? unserialize($adminData->roles) : [];
                
            global $subadminAccess;
            $accessControlArray = $subadminAccess;
                
            if (!is_array($accessControlArray)) {
                return response()->json(['message' => 'Access control data is missing or invalid', 'status' => 500], 500);
            }
                
            $accessArray = [];
            foreach ($accessControlArray as $key => $ac) {
                $accessArray[$key] = $ac; // Start with the original sub-array
                
                // Override with $accessData if available
                if (isset($accessData[$key])) {
                    foreach ($accessData[$key] as $accessKey => $accessValue) {
                        $accessArray[$key][$accessKey] = $accessValue;
                    }
                }
            }
                    
                    
            if($accessArray['7']['Edit'] == 0){
                return Response(['response' => 'You are not allowed to access this page.', 'message' => 'You are not allowed to access this page.', 'status' => 500], 200);
            }
        }
        
        
        if(!empty($request->all())){
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'code' => 'required',
                'symbol' => 'required',
            ]);
            
            if($validator->fails()){
                return Response(['response' => $validator->errors(), 'message' => 'error', 'status' => 500], 200);
            } else{
                Currency::where('id', $id)->update([
                    'name' => $request->name,
                    'code' => $request->code,
                    'symbol' => $request->symbol,
                ]);
                
                $currencyData = Currency::where('id', $id)->first();
                return Response(['response' => $currencyData , 'message'=> 'success' , 'status'=> 200 ],200);
            }
        }else{
             return Response(['response' => $currencyData , 'message' => 'sucess', 'status'=>200],200);
        }
    }
    
    public function is_default($id){
        if(!empty($id)){
            $data = Currency::where('id', $id)->first();
            if($data->status != 1){
                return Response(['response' => '', 'message' => 'Deactivated currency cannot be set as default currency', 'status' => 500], 200);
            }
            Currency::where('id', '!=', 0)->update([
                        'is_default' => 0,
                    ]);
            Currency::where('id',$id)->update([
                        'is_default' => 1,
            ]);

              
                $Keyword = Currency::where('id', '!=', 0)->get();
            return Response(['response' => $Keyword, 'message' => 'success', 'status' => 200], 200);
        }
        else{
            return Response(['response' => 'No record selected', 'message' => 'error', 'status' => 500], 200);
        }
    }
    
    // public function currency_deactivate($id) {
    //     if($id != ''){
    //         Currency::where('id', $id)->update([
    //             'status' => 0,
    //         ]);
            
    //         return Response(['response' => 'De-activated Successfully', 'message' => 'De-activated Successfully', 'status' => 200], 200);
    //     }
    //     return Response(['response' => 'Id not found', 'message' => 'Id not found', 'status' => 500], 200);
    // }
    
}
