<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Core\ComplianceGroup;
use Illuminate\Http\Request;

class ComplianceGroupController extends Controller
{
    public function index(Request $request)
    {
        $query = ComplianceGroup::query();

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('code', 'like', "%{$search}%");
            });
        }

        $groups = $query->latest()->paginate(15);

        return view('admin.compliance-groups.index', compact('groups'));
    }

    public function create()
    {
        return view('admin.compliance-groups.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:compliance_groups,code',
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        ComplianceGroup::create($validated);

        return redirect()->route('admin.compliance-groups.index')
            ->with('success', 'Compliance Group created successfully.');
    }

    public function show(ComplianceGroup $complianceGroup)
    {
        $complianceGroup->load([
            'complianceTypes' => function ($query) {
                $query->orderBy('priority')->orderBy('name');
            }
        ]);

        // Calculate Stats for each Type (similar to Dashboard)
        $activeSession = \App\Models\Core\FinancialSession::where('is_active', true)->first();
        $moduleStats = [];

        if ($activeSession) {
            $totalCompanies = $activeSession->companies()->count();

            foreach ($complianceGroup->complianceTypes as $type) {
                $pendingCount = 0;

                // Pending Logic
                if ($type->code === 'ADT1') {
                    $filedCount = \App\Models\Compliances\Adt1Compliance::where('financial_session_id', $activeSession->id)
                        ->where('status', 'Filed')
                        ->whereHas('company', function ($q) use ($activeSession) {
                            $q->whereHas('financialSessions', function ($sub) use ($activeSession) {
                                $sub->where('financial_sessions.id', $activeSession->id);
                            });
                        })
                        ->count();
                    $pendingCount = $totalCompanies - $filedCount;
                }

                $moduleStats[$type->id] = [
                    'pending' => $pendingCount,
                    'filed' => $totalCompanies - $pendingCount // approximate
                ];
            }
        }

        return view('admin.compliance-groups.show', compact('complianceGroup', 'moduleStats'));
    }

    public function edit(ComplianceGroup $complianceGroup)
    {
        return view('admin.compliance-groups.edit', compact('complianceGroup'));
    }

    public function update(Request $request, ComplianceGroup $complianceGroup)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:compliance_groups,code,' . $complianceGroup->id,
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->has('is_active');

        $complianceGroup->update($validated);

        return redirect()->route('admin.compliance-groups.index')
            ->with('success', 'Compliance Group updated successfully.');
    }

    public function destroy(ComplianceGroup $complianceGroup)
    {
        $complianceGroup->delete();

        return redirect()->route('admin.compliance-groups.index')
            ->with('success', 'Compliance Group deleted successfully.');
    }
}
