<?php

namespace App\Http\Controllers;

use DB;
use App\Models\Fund;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\EmpPersonalDetails;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class FundsController extends Controller
{

    public function index(Request $request)
    {
        $query = Fund::where('del', '0');
        $query = $this->applyCustomerWorkspaceFilter($query);   
        $query->latest('id');
        // Apply search filter across all columns
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'like', '%' . $searchTerm . '%')
                  ->orWhere('percentage', 'like', '%' . $searchTerm . '%')
                  ->orWhere('usi_number', 'like', '%' . $searchTerm . '%');
            });
        }
        $funds = $query->get();
        return $this->withCount($funds, 'Get Funds List Successfully');
    }



    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        $user = auth()->user();
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'percentage' => 'required|numeric|between:0,999999',
            'usi' => 'required',
            'usi_number' => 'required_if:usi,1|nullable',
        ],
        [
            'usi_number.required_if' => "The usi number field is required.",
        ]);
        
        if ($validator->fails()) {

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

        } else {
          
            $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();  
            }
           $validatedData =  $validator->validated();
           $validatedData['customer_id'] =  $auth_id;
           $validatedData['workspace_id'] =  $workspace_id;
           Fund::insert($validatedData);
    
           return $this->message('Funds save successfully');
        }        

    }

    public function show($id)
    {
        //
    }

    public function funds_edit(Request $request)
    {
        $id=$request->id;
        $userTable = $this->getUserTable();
        $Fund = Fund::find($id);
        if (
            $userTable == "customer" && ($Fund->workspace_id != auth()->user()->current_workspace_id || $Fund->customer_id != auth()->user()->id)
        ) {
            return $this->message('You do not have access to this Fund', 403);
        }
        if ($userTable == "emp" && ($Fund->customer_id != auth()->user()->customer_id || $Fund->workspace_id != auth()->user()->workspace_id)) {
            
            return $this->message('You do not have access to this Fund', 403);
        }
        $data['Funds'] = $Fund;
        return $this->success($data,'Fund get successfully');
    }

    public function funds_update(Request $request)
    {
        $user = auth()->user();
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'title' => 'required',
            'percentage' => 'required|numeric',
            'usi' => 'required',
            'usi_number' => 'required_if:usi,1|nullable',
        ],
        [
            'usi_number.required_if' => "The usi number field is required.",
        ]);
        
        if ($validator->fails()) {

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

        } else {

            $id=$request->id;
            $userTable = $this->getUserTable();
            $Fund = Fund::find($id);
            if (
                $userTable == "customer" && ($Fund->workspace_id != auth()->user()->current_workspace_id || $Fund->customer_id != auth()->user()->id)
            ) {
                return $this->message('You do not have access to this Fund', 403);
            }
            if ($userTable == "emp" && ($Fund->customer_id != auth()->user()->customer_id || $Fund->workspace_id != auth()->user()->workspace_id)) {
                
                return $this->message('You do not have access to this Fund', 403);
            }
            $validatedData =  $validator->validated();

            Fund::where('id', $id)->update($validatedData);

            return $this->message('Funds Updated Successfully');
        }        

    }

    public function funds_delete(Request $request)
    {
        $id=$request->id;
          $userTable = $this->getUserTable();
        $Fund = Fund::find($id);
        if ($userTable == "customer" && ($Fund->workspace_id != auth()->user()->current_workspace_id || $Fund->customer_id != auth()->user()->id)) {
            return $this->message('You do not have access to this Fund', 403);
        }
        if ($userTable == "emp" && ($Fund->customer_id != auth()->user()->customer_id || $Fund->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this Fund', 403);
        }
        $Fund->del='1';
        $Fund->save();

        return $this->message('Funds Deleted Successfully');
    }
}
