<?php

namespace App\Http\Controllers\Accounting;

use Illuminate\Http\Request;
use App\Constants\Accounting;
use App\Models\Accounting\FeeType;
use App\Models\Accounting\ClassFee;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use App\Services\Accounting\ClassFeesService;
use App\Services\Accounting\FeeInvoiceService;

class ClassFeeController extends Controller
{
    protected $classFeesService;
    protected $feeInvoiceService;

    public function __construct(ClassFeesService $classFeesService, FeeInvoiceService $feeInvoiceService)
    {
        $this->classFeesService = $classFeesService;
        $this->feeInvoiceService = $feeInvoiceService;
    }

    public function index()
    {
        $this->authorize('accounting.class-wise-fees.view');
        $classFees = $this->classFeesService->getClassFees();
        return view('pages.accounting.class_fees.index', compact('classFees'));
    }

    public function create()
    {
        $this->authorize('accounting.class-wise-fees.create');
        $data = $this->classFeesService->getRelatedData();
        return view('pages.accounting.class_fees.create', $data);
    }

    public function store(Request $request)
    {
        // dd($request->all()); An error occurred while creating the class fee. Please try again.
        try {
            $this->authorize('accounting.class-wise-fees.create');
            $classFees = $this->classFeesService->store($request);
            if ($classFees->isEmpty()) {
                return redirect()->route('class_fees.index')->with('warning', 'Class Fee already created for this class\year. You can update it from the list.');
            }
            
            return redirect()->route('class_fees.index')->with('success', 'Class Fee created successfully.');
        } catch (\Throwable $e) {
            Log::error('Failed to create class fee: ' . $e->getMessage());
            return redirect()->route('class_fees.index')->with('error', 'An error occurred while creating the class fee. Please try again.');
        }
    }
    

    public function show($class_id, $academic_year_id)
    {
        $this->authorize('accounting.class-wise-fees.view');
        $data = $this->classFeesService->getRelatedData();
        $data['fee_details'] = $this->classFeesService->getFeeDetails($class_id, $academic_year_id);
        // dd($data);
        // return view('pages.accounting.class_fees.show', $data);

         // Get all fee types (e.g., Tuition, Transport, etc.)
        $feeTypes = FeeType::where('status',1)->select('id','title','code')->get()->unique('code');

        // Fetch fee data for given class/year
        $feeData = ClassFee::where('student_class_id', $class_id)
                    ->where('academic_year_id', $academic_year_id)
                    ->get();

        // Structure data: [fee_type_code][month] = amount
        $structuredData = [];
        foreach ($feeData as $item) {
            $feeTypeCode = $item->feeType->code; // Assuming FeeStructure has feeType() relation
            $structuredData[$feeTypeCode][$item->month] = $item->amount;
        }

        $fee_details = $this->classFeesService->getFeeDetails($class_id, $academic_year_id);
        return view('pages.accounting.class_fees.show', [
            'feeTypes' => $feeTypes,
            'fee_details' => $fee_details,
            'structuredData' => $structuredData,
        ]);
    }

    public function edit($class_id, $academic_year_id)
    {
        $this->authorize('accounting.class-wise-fees.edit');

        $fee_details = $this->classFeesService->getFeeDetails($class_id, $academic_year_id);

         // Get all fee types (e.g., Tuition, Transport, etc.)
        $feeTypes = FeeType::where('status',1)->select('id','title','code')->get()->unique('code');

        // Fetch fee data for given class/year
        $feeData = ClassFee::where('student_class_id', $class_id)
                    ->where('academic_year_id', $academic_year_id)
                    ->get();

        // Structure data: [fee_type_code][month] = amount
        $structuredData = [];
        foreach ($feeData as $item) {
            $feeTypeCode = $item->feeType->code; // Assuming FeeStructure has feeType() relation
            $structuredData[$feeTypeCode][$item->month] = $item->amount;
        }

        $fee_details = $this->classFeesService->getFeeDetails($class_id, $academic_year_id);
        return view('pages.accounting.class_fees.edit', [
            'feeTypes' => $feeTypes,
            'fee_details' => $fee_details,
            'structuredData' => $structuredData,
        ]);

    }

    public function copy($class_id, $academic_year_id)
    {
        $this->authorize('accounting.class-wise-fees.edit');

        $data = $this->classFeesService->getRelatedData();
        $data['fee_details'] = $this->classFeesService->getFeeDetails($class_id, $academic_year_id);
        $data['selectedFeeTypes'] = $this->classFeesService->getSelectedFeeTypes($class_id, $academic_year_id);
        return view('pages.accounting.class_fees.copy', $data);
    }

    public function update(Request $request)
    {
        try {
            $this->authorize('accounting.class-wise-fees.edit');
            $this->classFeesService->update($request);
            return redirect()->route('class_fees.index')->with('success', 'Class Fees updated successfully.');
        } catch (\Throwable $e) {
            Log::error('Failed to update class fees: ' . $e->getMessage(), [
                'request' => $request->all(),
                'exception' => $e,
            ]);

            return redirect()->route('class_fees.index')->with('error', 'An error occurred while updating class fees. Please try again.');
        }
    }


    public function destroy($class_id, $academic_year_id)
    {
        $this->authorize('accounting.class-wise-fees.delete');
        $this->classFeesService->delete($class_id, $academic_year_id);
        return redirect()->route('class_fees.index')->with('success', 'Class Fee deleted successfully.');
    }
}
