<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuditLogController extends Controller
{
    /**
     * GET /audit-logs
     * List audit logs with filters & role-based scope
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();

            if (!$user || !in_array($user->role, ['super_admin', 'franchise_admin', 'franchise_editor'])) {
                return ApiResponse::error('Forbidden', 403);
            }

            $query = AuditLog::query();

            // ✅ ENFORCE STRICT FRANCHISEE ISOLATION
            if ($user->role === 'super_admin') {
                // Super admin sees ONLY system-level logs (franchisee_id = null)
                $query->whereNull('franchisee_id');
            } else {
                // Franchisee sees ONLY their own logs - NO OVERRIDE ALLOWED
                $query->where('franchisee_id', $user->franchisee_id);
            }

            // 🔹 Filters (but respect role-based isolation)
            if ($request->filled('user_id')) {
                $query->where('user_id', $request->user_id);
            }

            // 🔴 REMOVED: Don't allow franchisee_id filter - enforce isolation
            // if ($request->filled('franchisee_id')) {
            //     $query->where('franchisee_id', $request->franchisee_id);
            // }

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

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

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

            if ($request->filled('q')) {
                $term = $request->q;
                $query->where(function ($sub) use ($term) {
                    $sub->where('action', 'like', "%{$term}%")
                        ->orWhere('description', 'like', "%{$term}%")
                        ->orWhere('ip_address', 'like', "%{$term}%")
                        ->orWhere('user_name', 'like', "%{$term}%")
                        ->orWhere('franchise_name', 'like', "%{$term}%");
                });
            }

            // 🔹 Pagination & sorting
            $perPage = (int) $request->get('per_page', 25);
            $logs = $query->orderBy('created_at', 'desc')->paginate($perPage);

            return ApiResponse::success([
                'logs' => $logs->items(),
                'meta' => [
                    'current_page' => $logs->currentPage(),
                    'last_page' => $logs->lastPage(),
                    'per_page' => $logs->perPage(),
                    'total' => $logs->total(),
                ],
            ]);
        } catch (\Exception $e) {
            return ApiResponse::error($e->getMessage());
        }
    }

    /**
     * GET /audit-logs/{id}
     * View a single log entry
     */
    public function show(Request $request, $id)
    {
        try {
            $log = AuditLog::findOrFail($id);
            $user = Auth::user();

            // ✅ ENFORCE ROLE-BASED ACCESS CONTROL
            if ($user->role === 'super_admin') {
                // Super admin can only view system-level logs (franchisee_id = null)
                if ($log->franchisee_id !== null) {
                    return ApiResponse::error('Forbidden', 403);
                }
            } else {
                // Franchisee can only view their own logs
                if ($log->franchisee_id !== $user->franchisee_id) {
                    return ApiResponse::error('Forbidden', 403);
                }
            }

            return ApiResponse::success($log);
        } catch (\Throwable $e) {
            return ApiResponse::exception($e);
        }
    }
}
