<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Settings;
use App\Models\ReportLog;
use Illuminate\Http\Request;
use App\Models\AttendanceLog;
use App\General\SettingsClass;
use App\Models\EmpPersonalDetails;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Sites;
use GrahamCampbell\ResultType\Success;
use Illuminate\Support\Facades\Auth;
use Intervention\Image\ImageManager;
use Illuminate\Support\Facades\Validator;
class SettingsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $userTable = $this->getUserTable();
        $auth_id =0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }
   
        $settings = Settings::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->get();
        $webLogo  = SettingsClass::getOptionValue('_web_logo', $settings);
      $data['settings']=$settings;
      $data['weblogo']=$webLogo;

      if ($data['settings']->isEmpty() ) {
        return $this->message('Required data not found', 404);
    }
        return $this->success($data,'Setting Get Successfully');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $meta_ = $request->only([
            '_web_logo',
            '_financial_year_end_date',
            '_financial_year_start_date',
            '_financial_year_end_month',
            '_financial_year_start_month',
            '_working_days',
            '_time_zone',
        ]);
        $userTable = $this->getUserTable();
        $auth_id =0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first(); 
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }
   
        $settings = Settings::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->get();

        if ($request->hasFile('_web_logo')) {
            $image = $request->file('_web_logo');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('upload/images'), $imageName);
            $meta_['_web_logo'] = 'upload/images/' . $imageName;
        } else {
            $webLogo = SettingsClass::getOptionValue('_web_logo', $settings);
            if ($webLogo) {
                $meta_['_web_logo'] = $webLogo;
            }
        }
  
        $settingsMeta = [];

        foreach ($meta_ as $option => $value) {
            if ($value !== null) {
                $settingsMeta[] = [
                    'option' => $option,
                    'value' => $value,
                    'customer_id'=>$auth_id,
                    'workspace_id'=>$workspace_id
                ];
            }
        }
     
        DB::table('settings')->whereIn('option', [
            '_financial_year_end_date',
            '_financial_year_start_date',
            '_financial_year_end_month',
            '_financial_year_start_month',
            '_working_days',
            '_time_zone',
            '_web_logo',
        ])->where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->delete();
        $setting=DB::table('settings')->insert($settingsMeta);

        $setting= Settings::where('customer_id',$auth_id)->where('workspace_id',$workspace_id)->get();

        return $this->success($setting,'Setting Update Successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function getInternalEmployeeRosterSetting(){
        $user = auth()->user();
        $userTable = $this->getUserTable();
        $auth_id =0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
            
            
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }
        $roster_setting = DB::table('settings')
        ->where('customer_id', $auth_id)
        ->where('workspace_id', $workspace_id)
        ->whereIn('option', [
            'roster_setting_title',
            'roster_setting_paid_break',
            'roster_setting_color_code',
            'roster_setting_start_time',
            'roster_setting_end_time',
            'roster_setting_description',
            'roster_setting_working_hours',
            'roster_setting_working_days',
            'roster_setting_number_of_days',
        ])->select('option','value','customer_id','workspace_id')->get();

        $roster_setting=$roster_setting;

        return $this->success($roster_setting,'Roster Setting Get Successfully');
    }
    
    public function internalEmployeeRosterSetting(Request $request){

       
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'paid_break' => 'required|integer|min:0',
            'color_code' => 'nullable|regex:/^#[0-9a-fA-F]{6}$/',
            'start_time' => 'required',
            'end_time' => 'required',
            'description' => 'nullable',
            'working_days' => 'required|array',
            'working_hours' => 'nullable|numeric',
            'number_of_days' => 'required|integer|min:1|max:365',
        ],
        [
            'working_days.required' => 'Please select one or more working days'
        ]
        );
      
        if ($validator->fails()) {

            $error = $validator->errors()->first();
            return $this->error($error,422);
        }

        $meta = $request->only([
            'title',
            'paid_break',
            'color_code',
            'start_time',
            'end_time',
            'description',
            'working_days',
            'working_hours',
            'number_of_days',
        ]);
       
        $user = auth()->user();
        
        $userTable = $this->getUserTable();
        $auth_id =0;
        $workspace_id = 0;
        if ($userTable === "customer") {
            $auth_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
            
            
        }
        if ($userTable === "emp") {
            $auth_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }

        DB::table('settings')
            ->where('customer_id', $auth_id)
            ->where('workspace_id', $workspace_id)
            ->whereIn('option', [
                'roster_setting_title',
                'roster_setting_paid_break',
                'roster_setting_color_code',
                'roster_setting_start_time',
                'roster_setting_end_time',
                'roster_setting_description',
                'roster_setting_working_days',
                'roster_setting_working_hours',
                'roster_setting_number_of_days',
            ])
            ->delete();
         
        $settingsMeta = [];

        foreach ($meta as $option => $value) {
            if ($value !== null) {
                if($option == 'working_days'){
                    $value = implode(',', $value);
                }
                $settingsMeta[] = [
                    'option' => "roster_setting_".$option,
                    'value' => $value,
                    'customer_id'=> $auth_id,
                    'workspace_id'=> $workspace_id,
                ];
            }
        }

        DB::table('settings')->insert($settingsMeta);

        $data['settingsMeta']=$settingsMeta;

        return $this->success($data,'Internal Employee Roster Setting Saved.');

    }

    public function getAttendanceLogs(Request $request)
    {

        $userTable = $this->getUserTable();
        $workspace_id = 0;
        $customer_id = 0;
        if ($userTable === "customer") {
            $customer_id = Auth::user()->id;
            $workspace_id = Auth::user()->current_workspace_id;  
            $authPersonalDetails = User::where('id', Auth::user()->id)->first();
        }
        if ($userTable === "emp") {
            $customer_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
            $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();  
        }

        $query = AttendanceLog::query()
        ->where('customer_id', $customer_id)
        ->where('workspace_id', $workspace_id);

        if ($request->filled('first_name')) {
            $query->whereHas('EmpPersonalDetails', function($q) use ($request) {
                $q->where('first_name', 'like', '%' . $request->first_name . '%');
            });
        }

        if ($request->filled('site')) {
            $query->whereHas('Sites', function($q) use ($request) {
                $q->where('title', 'like', '%' . $request->site . '%');
            });
        }

        if ($request->filled('date')) {
            $query->whereDate('date', '=', $request->date);
        }
  
        $query->with(['EmpPersonalDetails','EmpCompanyDetails','Sites']);
        $query->orderBy('id', 'desc');

        $array_filter =  json_decode($request->filter, true);
        $filters = [
          'first_name' => $array_filter['first_name'] ?? '', 
          'middle_name' => $array_filter['middle_name'] ?? '',
          'last_name' => $array_filter['first_name'] ?? '',
          'employee_email' => $array_filter['last_name'] ?? '',
          'compeleted' => $array_filter['first_name'] ?? '',
          'status' => $array_filter['compeleted'] ?? '',
        ];

        return $this->WithFilter($query, $filters,'Get Attendance List Successfully');

    }

    public function filter($filters,$query)
    {
     
        foreach ($filters as $filterName => $filterValue) {
            if ($filterValue != null ||  $filterValue !="" ) {
                switch ($filterName) {
                    case 'first_name':
                        $filterValue  = explode(" ",$filterValue);
                    
                        if(count($filterValue) == 1)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->orWhere('middle_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->orWhere('last_name', 'like', '%' . $filterValue[0] . '%');
                            });

                        }

                        if(count($filterValue) == 2)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->where('middle_name', 'like', '%' . $filterValue[1] . '%');
                                $subquery->where('last_name', 'like', '%' . $filterValue[1] . '%');
                            });

                        }

                        if(count($filterValue) == 3)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->where('middle_name', 'like', '%' . $filterValue[1] . '%');
                                $subquery->where('last_name', 'like', '%' . $filterValue[2] . '%');
                            });
                        }
                    break;
                    case 'title':
                        $query->whereHas('sites', function ($subquery) use ($filterValue) {
                            $subquery->where('title', 'like', '%' . $filterValue . '%');
                        });
                    break;
                    case 'date':
                        $query->where('date','=',formatDate($filterValue));
                    break;    
                  }
              }
        }

        return $query;
    }
    public function getReportsLogs(Request $request)
    {
    $query = ReportLog::query();

    if ($request->filled('filter')) {
        $query = $this->Reportfilter(json_decode($request->filter, true), $query);
    }
    $query->with(['emppersonaldetails', 'empcompanydetails']);

    $count = $query->count();
    $start = $request->input('from', 0);
    $query->offset($start)->limit(10)->orderBy('id', 'desc'); // Moved orderBy to the correct position

    $query_result = $query->get();
    $data = [
        'attendances' => $query_result,
    ];

    $array_filter = json_decode($request->filter, true);
    $filters = [
        'first_name' => $array_filter['first_name'] ?? '',
        'middle_name' => $array_filter['middle_name'] ?? '',
        'last_name' => $array_filter['last_name'] ?? '', // Corrected key
        'employee_email' => $array_filter['employee_email'] ?? '', // Corrected key
        'completed' => $array_filter['completed'] ?? '', // Corrected key
        'status' => $array_filter['status'] ?? '', // Corrected key
    ];

    return response()->json([
        'message' => 'Get Attendance List Successfully',
        'data' => $data,
        'count' => $count,
        'filters' => $filters
    ], 200);
    }

    public function Reportfilter($filters,$query)
    {
      
        foreach ($filters as $filterName => $filterValue) {
            if ($filterValue != null ||  $filterValue !="" ) {
                switch ($filterName) {
                    case 'first_name':
                        $filterValue  = explode(" ",$filterValue);
                    
                        if(count($filterValue) == 1)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->orWhere('middle_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->orWhere('last_name', 'like', '%' . $filterValue[0] . '%');
                            });

                        }

                        if(count($filterValue) == 2)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->where('middle_name', 'like', '%' . $filterValue[1] . '%');
                                $subquery->where('last_name', 'like', '%' . $filterValue[1] . '%');
                            });

                        }

                        if(count($filterValue) == 3)
                        {
                            $query->whereHas('empPersonalDetails', function ($subquery) use ($filterValue) {
                                $subquery->where('first_name', 'like', '%' . $filterValue[0] . '%');
                                $subquery->where('middle_name', 'like', '%' . $filterValue[1] . '%');
                                $subquery->where('last_name', 'like', '%' . $filterValue[2] . '%');
                            });
                        }
                    break;
                    case 'report_type':
                        $query->where('report_type', $filterValue);
                        break;
                        
                    case 'date':
                          
                            $query->whereDate('created_at', '=', $filterValue);
                            break;   
                  }
              }
        }

        return $query;
    }
}
