<?php

namespace App\Http\Controllers\Admission;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use App\Models\Academic\StudentClass;
use App\Models\Admission\AdmissionFee;
use Yajra\DataTables\Facades\DataTables;

class AdmissionFeeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $this->authorize('online-admission.applicant-list');

        if ($request->ajax()) {
            $data = AdmissionFee::with([
                    'studentClass:id,class_name'
                ])
                ->orderBy('student_class_id', 'asc');

            return DataTables::of($data)
                ->addIndexColumn()

                // 👇 Add combined full name

                ->addColumn('admission_fee', function ($row) {
                    return $row->admission_fee ?? '-';
                })
                ->addColumn('class_name', function ($row) {
                    return $row->studentClass->class_name ?? '-';
                })
                ->addColumn('action', function ($row) {
                    $destroy = route('admission-fee.destroy', $row->id);
                    return '<div class="d-flex justify-content-center">
                                <a href="'.$destroy.'" class="btn btn-sm btn-soft-info" target="_blank" title="View">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </div>';
                })

                ->rawColumns(['action'])

                // 👇 Custom sort & search
                ->filterColumn('admission_fee', function($query, $keyword) {
                    $query->where('admission_fee', 'like', "%{$keyword}%");
                })
                ->filterColumn('class_name', function($query, $keyword) {
                    $query->whereHas('studentClass', function($q) use ($keyword) {
                        $q->where('class_name', 'like', "%{$keyword}%");
                    });
                })
                ->make(true);
        }
        $studentClasses = StudentClass::pluck('class_name', 'id');
            
        return view('pages.admission.admission-fees.index', compact('studentClasses'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // 1. Validate incoming request
        
        $validated = $request->validate([
            'student_class_id' => [
                'required',
                'exists:student_classes,id',
                Rule::unique('admission_fees')
                    ->where('branch_id', auth()->user()->branch_id),
            ],
            'admission_fee' => 'required|numeric|min:0',
        ]);

        // 2. Add extra fields (if required)
        $validated['branch_id'] = auth()->user()->branch_id;

        // 3. Store data
        $admissionFee = AdmissionFee::create($validated);

        // 4. Redirect back with success
        return redirect()->back()->with('success', 'Admission fee created successfully!');
    }


    /**
     * Update the specified resource in storage.
     */
    
    public function update(Request $request)
    {
        $validated = $request->validate([
            'student_class_id' => [
                'required',
                'exists:student_classes,id',
                Rule::unique('admission_fees')
                    ->ignore($request->id) // 🔹 ignore current record
                    ->where('branch_id', auth()->user()->branch_id),
            ],
            'admission_fee' => 'required|numeric|min:0',
        ]);

        // Add extra fields
        $validated['branch_id'] = auth()->user()->branch_id;

        // Update the record
        AdmissionFee::where('id', $request->id)->update($validated);

        return redirect()->back()->with('success', 'Admission Fee updated successfully!');
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        // Find the record or fail
        $admissionFee = AdmissionFee::findOrFail($id);

        // Delete the record
        $admissionFee->delete();

        // Redirect back with success message
        return redirect()->back()->with('success', 'Admission Fee deleted successfully!');
    }
}
