<?php

namespace App\Http\Controllers;

use App\Models\Classe;
use App\Models\Section;
use App\Models\Student;
use Illuminate\Http\Request;
use App\Models\Fee_structure;
use App\Models\Student_assign_fee;
use App\Models\Student_fee_detail;
use Illuminate\Support\Str;

// Import Exception class for error handling

class FeeMgtController extends Controller
{
    public function show_fee_management()
    {
        $students = Student::where('status', 'active')
            ->with(['classes', 'sections', 'latestAdmission'])
            ->get();

        $classes  = Classe::all();
        $sections = Section::all();
        $fee_structures  = Fee_structure::with('class')->get();

        return view('stdFeeMgt.fee-management', compact('students', 'classes', 'sections', 'fee_structures'));
    }



    public function fetch_student_fee_assign(Request $request)
    {
        $classId = $request->input('class_id');
        $studentId = $request->input('student_id');

        $assignedFees = Student_assign_fee::where('student_id', $studentId)
            ->where('class_id', $classId)
            ->first();

        $html = '';
        $totalAssignedAmount = 0;

        $feeColumns = [
            'admission_fee',
            'promotion_fee',
            'scholarship_fee',
            'sport_fee',
            'tuition_fee',
            'lab_fee',
            'exam_fee',
            'board_fee',
            'entertainment_fee',
            'other_fee',
            'books_charges',
            'annual_charges',
            'second_time_fee'
        ];

        if ($assignedFees) {
            foreach ($feeColumns as $column) {
                $value = $assignedFees->$column;
                $isChecked = (!is_null($value) && $value > 0) ? 'checked' : '';
                $amountValue = !is_null($value) ? $value : '';

                $label = Str::title(str_replace('_', ' ', $column));

                $html .= '<label class="flex items-center p-4 border rounded shadow-sm cursor-pointer mb-2">';
                $html .= '<input type="checkbox" name="fees[' . $column . '][active]" class="mr-2 feeCheckbox" ' . $isChecked . ' />';
                $html .= '<span class="w-48">' . $label . '</span>';
                // ✅ Added class="amountInput" below:
                $html .= '<input type="number" step="0.01" name="fees[' . $column . '][amount]" value="' . $amountValue . '" class="border p-1 w-32 ml-4 amountInput" />';
                $html .= '</label>';

                if ($isChecked) {
                    $totalAssignedAmount += $value;
                }
            }
        } else {
            $html = '<p class="text-red-500">No fee assigned for this student and class.</p>';
        }

        return response()->json([
            'html' => $html,
            'total_assigned' => $totalAssignedAmount
        ]);
    }

    public function fetch_fee_structure(Request $request)
    {
        $classId = $request->input('class_id');

        $feeStructures = Fee_structure::with('class')
            ->when($classId, function ($query) use ($classId) {
                return $query->where('class_id', $classId);
            })
            ->get();

        $html = '';
        $feeIds = []; // Array to hold fee structure IDs

        if ($feeStructures->isNotEmpty()) {
            foreach ($feeStructures as $feeStructure) {
                $feeIds[] = $feeStructure->id; // Collect ID

                $feeType = $feeStructure->class->name . ' - ' . Str::title(str_replace('_', ' ', $feeStructure->fee_type));
                $amount = number_format($feeStructure->amount, 2);

                $html .= '<label class="flex items-center justify-between p-4 border rounded shadow-sm cursor-pointer">';
                $html .= '<div class="flex items-center">';
                $html .= '<input type="checkbox" name="fees[' . $feeStructure->id . '][amount]" value="' . $feeStructure->amount . '" class="mr-2 feeCheckbox" />';
                $html .= '<input type="hidden" name="fees[' . $feeStructure->id . '][type]" value="' . $feeStructure->fee_type . '" />';
                $html .= '<span class="text-gray-800 font-medium">' . $feeType . '</span>';
                $html .= '</div>';
                $html .= '<div class="text-green-700 font-bold">';
                $html .= 'Rs. <input type="number" step="0.01" name="fees[' . $feeStructure->id . '][editable_amount]" value="' . $feeStructure->amount . '" class="editableAmountInput border border-gray-300 px-2 py-1 rounded w-24" />';
                $html .= '</div>';
                $html .= '</label>';
            }
        } else {
            $html = '<p class="text-red-500">No fee structures found.</p>';
        }

        // Return both HTML and fee IDs
        return response()->json([
            'html' => $html,
            'fee_ids' => $feeIds,
        ]);
    }

    public function fetch_fee_structure_promote_bulk(Request $request)
    {
        $classId = $request->input('class_id');

        $feeStructures = Fee_structure::with('class')
            ->when($classId, function ($query) use ($classId) {
                return $query->where('class_id', $classId);
            })
            ->get();

        $html = '';
        $feeIds = []; // Array to hold fee structure IDs

        if ($feeStructures->isNotEmpty()) {
            foreach ($feeStructures as $feeStructure) {
                $feeIds[] = $feeStructure->id; // Collect ID

                $feeType = $feeStructure->class->name . ' - ' . Str::title(str_replace('_', ' ', $feeStructure->fee_type));
                $amount = number_format($feeStructure->amount, 2);

                $html .= '<label class="flex items-center justify-between p-4 border rounded shadow-sm cursor-pointer">';
                $html .= '<div class="flex items-center">';
                $html .= '<input type="checkbox" name="fees[' . $feeStructure->id . '][amount]" value="' . $feeStructure->amount . '" class="mr-2 feeCheckbox" />';
                $html .= '<input type="hidden" name="fees[' . $feeStructure->id . '][type]" value="' . $feeStructure->fee_type . '" />';
                $html .= '<span class="text-gray-800 font-medium">' . $feeType . '</span>';
                $html .= '</div>';
                $html .= '<div class="text-green-700 font-bold">';
                $html .= 'Rs. <input type="number" step="0.01" name="fees[' . $feeStructure->id . '][editable_amount]" value="' . $feeStructure->amount . '" class="editableAmountInput border border-gray-300 px-2 py-1 rounded w-24" />';
                $html .= '</div>';
                $html .= '</label>';
            }
        } else {
            $html = '<p class="text-red-500">No fee structures found.</p>';
        }

        // Return both HTML and fee IDs
        return response()->json([
            'html' => $html,
            'fee_ids' => $feeIds,
        ]);
    }

    public function fetch_fee_structure_fee_bulk(Request $request)
    {
        $classId = $request->input('class_id');

        $feeStructures = Fee_structure::with('class')
            ->when($classId, function ($query) use ($classId) {
                return $query->where('class_id', $classId);
            })
            ->get();

        $html = '';
        $feeIds = [];

        if ($feeStructures->isNotEmpty()) {
            foreach ($feeStructures as $feeStructure) {
                $feeIds[] = $feeStructure->id;

                $feeType = Str::title(str_replace('_', ' ', $feeStructure->fee_type));
                $amount = number_format($feeStructure->amount, 2);

                $html .= '<label class="flex items-center justify-between p-4 border rounded shadow-sm cursor-pointer">';
                $html .= '<div class="flex flex-col w-full">';
                $html .= '<div class="flex items-center justify-between">';
                $html .= '<div class="flex items-center">';
                $html .= '<input type="checkbox" name="fees[' . $feeStructure->id . '][active]" value="1" class="mr-2 feeCheckbox" />';
                $html .= '<span class="text-gray-800 font-medium">' . $feeStructure->class->name . ' - ' . $feeType . '</span>';
                $html .= '</div>';
               /*  $html .= '<div class="text-green-700 font-bold">Rs ' . $amount . '</div>'; */
                $html .= '</div>';
                $html .= '<input type="hidden" name="fees[' . $feeStructure->id . '][type]" value="' . $feeStructure->fee_type . '">';
                $html .= '<input type="hidden" name="fees[' . $feeStructure->id . '][amount]" class="amountInput" value="' . $feeStructure->amount . '">';
                $html .= '</div>';
                $html .= '</label>';
            }
        } else {
            $html = '<p class="text-red-500">No fee structures found.</p>';
        }

        return response()->json([
            'html' => $html,
            'fee_ids' => $feeIds,
        ]);
    }


    public function searchStudents($searchTerm)
    {
        // $searchTerm = $request->input('term');
        $students = Student::with('guardian')
            ->where(function ($query) use ($searchTerm) {
                $query->where('student_name', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('reg_no', 'LIKE', "%{$searchTerm}%")
                    ->orWhere('father_cnic', 'LIKE', "%{$searchTerm}%")
                    ->orWhereHas('guardian', function ($query) use ($searchTerm) {
                        $query->where('guardian_contact', 'LIKE', "%{$searchTerm}%");
                    });
            })
            ->select('id', 'student_name', 'reg_no', 'father_cnic')
            ->limit(10)
            ->get();

        $formattedStudents = $students->map(function ($student) {
            return [
                'success' => true,
                'id' => $student->id,
                'text' => "{$student->student_name} (Reg: {$student->reg_no}) - CNIC: {$student->father_cnic} - Guardian: " .
                    ($student->guardian ? $student->guardian->guardian_contact : 'N/A')
            ];
        });

        return response()->json($formattedStudents);
    }
}
