<?php

namespace App\Http\Controllers;

use App\Models\ActivityLog;
use App\Models\UserMaster;
use App\Models\ActionMaster;
use App\Models\ChlVoucher;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Throwable;

class ActivityLogController extends Controller
{

    public function getActivityLogs(Request $request): JsonResponse
    {
        try {
            $query = ActivityLog::with(['user', 'action']);


            if ($request->filled('U_Id')) {
                $query->where('U_Id', $request->U_Id);
            }


            if ($request->filled('user_name')) {
                $userIds = UserMaster::where('Usr_Name', 'like', '%' . $request->user_name . '%')
                    ->orWhere('Usr_Email', 'like', '%' . $request->user_name . '%')
                    ->pluck('Usr_Id');
                if ($userIds->isNotEmpty()) {
                    $query->whereIn('U_Id', $userIds);
                } else {
                    $query->whereRaw('1 = 0');
                }
            }

            
            if ($request->filled('Menu_Id')) {
                $query->where('Menu_Id', $request->Menu_Id);
            }

            
            if ($request->filled('Action_Id')) {
                $query->where('Action_Id', $request->Action_Id);
            }

            
            if ($request->filled('action_name')) {
                $actionIds = ActionMaster::where('St_Name', 'like', '%' . $request->action_name . '%')
                    ->pluck('Act_Id');
                if ($actionIds->isNotEmpty()) {
                    $query->whereIn('Action_Id', $actionIds);
                } else {
                    $query->whereRaw('1 = 0');
                }
            }

            
            if ($request->filled('Tran_Id')) {
                $query->where('Tran_Id', $request->Tran_Id);
            }

            
            if ($request->filled('CV_No')) {
                $cvNo = $request->CV_No;

                
                $cvIds = ChlVoucher::withTrashed()
                          ->where('CV_No', $cvNo)
                          ->pluck('CV_Id');

                if ($cvIds->isNotEmpty()) {
                    $query->whereIn('Tran_Id', $cvIds);
                } else {
                    
                    $partialIds = ChlVoucher::withTrashed()
                                    ->where('CV_No', 'LIKE', '%' . $cvNo . '%')
                                    ->pluck('CV_Id');
                    if ($partialIds->isNotEmpty()) {
                        $query->whereIn('Tran_Id', $partialIds);
                    } else {
                        $query->whereRaw('1 = 0');
                    }
                }
            }

            
            if ($request->filled('from_date')) {
                $query->whereDate('Time_Stamp', '>=', $request->from_date);
            }

            
            if ($request->filled('to_date')) {
                $query->whereDate('Time_Stamp', '<=', $request->to_date);
            }

            
            if ($request->filled('date')) {
                $query->whereDate('Time_Stamp', $request->date);
            }

            
            if ($request->filled('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('Menu_Id', 'like', "%$search%")
                      ->orWhere('Tran_Id', 'like', "%$search%")
                      ->orWhereHas('user', function ($q2) use ($search) {
                          $q2->where('Usr_Name', 'like', "%$search%")
                             ->orWhere('Usr_Email', 'like', "%$search%");
                      })
                      ->orWhereHas('action', function ($q2) use ($search) {
                          $q2->where('St_Name', 'like', "%$search%");
                      });
                });
            }

            
            $sortBy = $request->get('sort_by', 'Time_Stamp');
            $sortOrder = $request->get('sort_order', 'desc');
            $allowedSorts = ['Act_Log', 'U_Id', 'Menu_Id', 'Time_Stamp', 'Action_Id', 'Tran_Id'];
            if (in_array($sortBy, $allowedSorts)) {
                $query->orderBy($sortBy, $sortOrder);
            } else {
                $query->orderBy('Time_Stamp', 'desc');
            }

            $logs = $query->get();

            $formattedData = $logs->map(function ($log) {
                return [
                    'Act_Log' => $log->Act_Log,
                    'U_Id' => $log->U_Id,
                    'User' => $log->user ? [
                        'Usr_Id' => $log->user->Usr_Id,
                        'Usr_Name' => $log->user->Usr_Name,
                        'Usr_Email' => $log->user->Usr_Email,
                    ] : null,
                    'Menu_Id' => $log->Menu_Id,
                    'Time_Stamp' => $log->Time_Stamp,
                    'formatted_time' => $log->Time_Stamp ? \Carbon\Carbon::parse($log->Time_Stamp)->format('d-m-Y H:i:s') : null,
                    'Action_Id' => $log->Action_Id,
                    'Action' => $log->action ? [
                        'Act_Id' => $log->action->Act_Id,
                        'St_Name' => $log->action->St_Name,
                    ] : null,
                    'Tran_Id' => $log->Tran_Id,
                ];
            });

            return response()->json([
                'success' => true,
                'message' => 'Activity logs fetched successfully',
                'total' => $logs->count(),
                'data' => $formattedData,
                'filters' => [
                    'U_Id' => $request->U_Id,
                    'user_name' => $request->user_name,
                    'Menu_Id' => $request->Menu_Id,
                    'Action_Id' => $request->Action_Id,
                    'action_name' => $request->action_name,
                    'Tran_Id' => $request->Tran_Id,
                    'CV_No' => $request->CV_No,
                    'from_date' => $request->from_date,
                    'to_date' => $request->to_date,
                    'date' => $request->date,
                    'search' => $request->search,
                    'sort_by' => $sortBy,
                    'sort_order' => $sortOrder,
                ]
            ]);

        } catch (Throwable $e) {
            Log::error('ActivityLog Fetch Error: ' . 'Something went wrong. Please try again later.');
            return response()->json([
                'success' => false,
                'message' => 'Something went wrong. Please try again later.',
                
            ], 500);
        }
    }
}
