<?php

namespace App\Http\Controllers\Hsc;

use Mpdf\Mpdf;
use App\Models\User;
use Illuminate\Support\Str;
use App\Models\GuardianInfo;
use Illuminate\Http\Request;
use App\Models\Academic\Group;
use App\Models\Academic\Shift;
use App\Models\Academic\Branch;
use App\Models\Student\SSCInfo;
use App\Models\Academic\Section;
use App\Models\Hsc\GroupSubject;
use App\Models\Hsc\HscAdmission;
use App\Models\Student\StudentInfo;
use App\Services\FileUploadService;
use App\Http\Controllers\Controller;
use App\Models\HrPayroll\Occupation;
use App\Services\StudentInfoService;
use Illuminate\Support\Facades\Hash;
use App\Models\Academic\ClassSection;
use App\Models\Academic\StudentClass;
use App\Models\StudentInfoSubjectClass;
use Yajra\DataTables\Facades\DataTables;
use App\Models\Guardian\GuardianRelation;
use Devfaysal\BangladeshGeocode\Models\Division;

class HscAdmissionController extends Controller
{
    protected $studentInfoService;
    protected $fileUploadService;
    public function __construct(FileUploadService $fileUploadService, StudentInfoService $studentInfoService)
    {
        $this->fileUploadService = $fileUploadService;
        $this->studentInfoService = $studentInfoService;
    }


    public function bulkSelectedData(Request $request)
    {
        $this->authorize('hsc.hsc-admission.store');

        $generateStudentId = $this->studentInfoService->generateStudentId();
        
        $studentClass = StudentClass::where('class_name', 'LIKE', '%eleven%')->first();
        $student_class_id = $studentClass ? $studentClass->id : 13;
        $shift_id = $request->input('shift_id');
        $section_id = $request->input('section_id');
        $ids = explode(',', $request->input('ids'));
        // Example: Retrieve the applicants
        $applicants = HscAdmission::whereIn('id', $ids)->get();
        $branch_id = auth()->user()->branch_id;

        foreach($applicants as $applicant){

            $group = Group::where('group_name', 'LIKE', '%' . $applicant->hscgruop . '%')->first();
            $group_id = $group ? $group->id : null;

            $admission_roll = $applicant->admission_roll;
            $session_year = $applicant->session_year;
            $first_name = $applicant->first_name;
            $last_name = $applicant->last_name ?? '';
            $applicant_mobile = $applicant->applicant_mobile;
            $blood_group = $applicant->blood_group;
            $nid = $applicant->nid;
            $dob = $applicant->dob;

            $gender = $applicant->gender;
            $religion = $applicant->religion;
            $profile_image = $applicant->profile_image;

            $board_select = $applicant->board_select;
            $passing_year = $applicant->passing_year;
            $institute_name = $applicant->institute_name;
            $ssc_roll_num = $applicant->ssc_roll_num;
            $ssc_reg_num = $applicant->ssc_reg_num;
            $ssc_session = $applicant->ssc_session;
            $ssc_gpa = $applicant->ssc_gpa;

            $father_name = $applicant->father_name;
            $father_mobile = $applicant->father_mobile;
            $father_occupation = $applicant->father_occupation;

            $mother_name = $applicant->mother_name;
            $mother_mobile = $applicant->mother_mobile;
            $mother_occupation = $applicant->mother_occupation;



            $present_division_id = $applicant->present_division_id;
            $present_district_id = $applicant->present_district_id;
            $present_upazila_id = $applicant->present_upazila_id;
            $present_union_id = $applicant->present_union_id;
            $present_address = $applicant->present_address;

            $permanent_division_id = $applicant->permanent_division_id;
            $permanent_district_id = $applicant->permanent_district_id;
            $permanent_upazila_id = $applicant->permanent_upazila_id;
            $permanent_union_id = $applicant->permanent_union_id;
            $permanent_address = $applicant->permanent_address;

        
            $selected = $applicant->selected;

            // data store start
            if($selected == 0){

                $lastRoll = StudentInfo::where('student_class_id', $student_class_id)->where('branch_id', auth()->user()->branch_id)->max('class_roll');

                $newRoll = $lastRoll ? $lastRoll + 1 : 1;
         
                $checkUser = User::where('phone_number', $applicant_mobile)->first();
                if ($checkUser) {
                    return redirect()->back()->with('error', 'User with this mobile number already exists.');
                }
                
                $user_store = new User();
                $user_store->first_name = $first_name;
                $user_store->last_name = $last_name;
                $user_store->name = $first_name.' '.$last_name;
                $user_store->slug = Str::slug($first_name.'-'.$last_name);
                $user_store->user_type = 'student';
                $user_store->branch_id = $branch_id;
                $user_store->phone_number = $applicant_mobile;
                $user_store->email = null;
                $user_store->password = Hash::make('12345678'); // Or generate random and send by email
                $user_store->save();
                
                $user_id = $user_store->id;
                
                $studentInfo = new StudentInfo();
                $studentInfo->student_id_no          = $generateStudentId ?? null; // or generate a unique one
                $studentInfo->user_id                = $user_id ?? null; // if available
                $studentInfo->branch_id              = $branch_id;
                $studentInfo->shift_id               = $shift_id;
                $studentInfo->section_id             = $section_id;
                $studentInfo->academic_year_id       = $applicant->academic_year_id ?? null;
                $studentInfo->first_name             = $first_name;
                $studentInfo->last_name              = $last_name;
                $studentInfo->name                   = $first_name . ' ' . $last_name;
                $studentInfo->age                    = null; // can be calculated from DOB if needed
                $studentInfo->gender                 = $gender;
                $studentInfo->blood_group            = $blood_group;
                $studentInfo->religion               = $religion;
                $studentInfo->date_of_birth          = $dob;
                $studentInfo->present_address        = $present_address;
                $studentInfo->permanent_address      = $permanent_address;
                $studentInfo->mobile_no              = $applicant_mobile;
                $studentInfo->email                  = $applicant->email ?? null;
                $studentInfo->birth_certi_no         = $nid;
                $studentInfo->profile_image          = $profile_image;
                $studentInfo->student_class_id       = $student_class_id;
                $studentInfo->version_id             = $applicant->version_id ?? 1;
                $studentInfo->group_id               = $group_id;
                $studentInfo->session                = $session_year;
                $studentInfo->admission_roll         = $admission_roll;
                $studentInfo->class_roll             = $newRoll;
                $studentInfo->year_admitted          = now()->format('Y'); // or custom
                $studentInfo->student_photo          = $profile_image;
                $studentInfo->dormitory_id           = $applicant->dormitory_id ?? null;
                $studentInfo->dorm_room_no           = $applicant->dorm_room_no ?? null;
                $studentInfo->father_name            = $father_name;
                $studentInfo->father_occupation      = $father_occupation;
                $studentInfo->father_mobile          = $father_mobile;
                $studentInfo->mother_name            = $mother_name;
                $studentInfo->mother_occupation      = $mother_occupation;
                $studentInfo->mother_mobile          = $mother_mobile;
                $studentInfo->guardian_name          = $applicant->guardian_name;
                $studentInfo->guardian_occupation    = $applicant->guardian_occupation ?? null;
                $studentInfo->guardian_mobile        = $applicant->guardian_mobile ?? null;
                $studentInfo->guardian_relationship  = $applicant->guardian_relation ?? null;
                $studentInfo->guardian_address       = $applicant->guardian_address ?? null;
                $studentInfo->present_division_id    = $present_division_id;
                $studentInfo->present_district_id    = $present_district_id;
                $studentInfo->present_upazila_id     = $present_upazila_id;
                $studentInfo->present_union_id       = $present_union_id;
                $studentInfo->permanent_division_id  = $permanent_division_id;
                $studentInfo->permanent_district_id  = $permanent_district_id;
                $studentInfo->permanent_upazila_id   = $permanent_upazila_id;
                $studentInfo->permanent_union_id     = $permanent_union_id;
                $studentInfo->created_by             = auth()->id();
                $studentInfo->updated_by             = auth()->id();
                $studentInfo->status                 = 'active'; // default value or use $applicant->status

                $studentInfo->save(); 


                $guardianInfo = new GuardianInfo();
                $guardianInfo->student_id             = $studentInfo->id;
                $guardianInfo->guardian_name          = $applicant->guardian_name ?? null;
                $guardianInfo->guardian_occupation    = $applicant->guardian_occupation ?? null;
                $guardianInfo->guardian_mobile        = $applicant->guardian_mobile ?? null;
                $guardianInfo->guardian_email         = $applicant->guardian_email ?? null;
                $guardianInfo->guardian_relationship  = $applicant->guardian_relation ?? null;
                $guardianInfo->guardian_address       = $applicant->guardian_address ?? null;
                $guardianInfo->password               = Hash::make('12345678');
                $guardianInfo->save();

                $ssc = new SSCInfo();
                $ssc->student_id                      = $studentInfo->id;
                $ssc->exam_name                       = $applicant->exam_name ?? 'ssc';
                $ssc->board                           = $board_select ?? null;
                $ssc->roll_no                         = $ssc_roll_num ?? null;
                $ssc->registration_no                 = $ssc_reg_num ?? null;
                $ssc->passing_year                    = $passing_year ?? null;
                $ssc->session                         = $ssc_session ?? null;
                $ssc->gpa                             = $ssc_gpa ?? null;
                $ssc->group_id                        = $group_id;
                $ssc->institute_name                  = $institute_name ?? null;
                $ssc->save();

                
                // Initialize
                $subjectMap = []; // key: subject_id, value: subject_type

                // Elective Subjects
                if (!empty($applicant->elective_subject1)) {
                    $subjectMap[$applicant->elective_subject1] = 'elective';
                }
                if (!empty($applicant->elective_subject2)) {
                    $subjectMap[$applicant->elective_subject2] = 'elective';
                }
                if (!empty($applicant->elective_subject3)) {
                    $subjectMap[$applicant->elective_subject3] = 'elective';
                }

                // Optional Subject
                if (!empty($applicant->optional_subject)) {
                    $subjectMap[$applicant->optional_subject] = 'optional';
                }

                // Compulsory Subjects
                $compulsorySubjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
                foreach ($compulsorySubjects as $compulsory) {
                    $subjectMap[$compulsory->subject_id] = 'compulsory';
                }

                // Insert
                foreach ($subjectMap as $subjectId => $subjectType) {
                    StudentInfoSubjectClass::create([
                        'student_info_id'   => $studentInfo->id,
                        'subject_id'        => $subjectId,
                        'student_class_id'  => $student_class_id,
                        'subject_type'      => $subjectType,
                    ]);
                }

                if (HscAdmission::where('id', $applicant->id)->exists()) {
                    HscAdmission::where('id', $applicant->id)->update(['selected' => 1]);
                }

            }
        }

        return redirect()->back()->with('success', 'Student information created successfully.');
        
    }




    public function index(Request $request)
    {
        $this->authorize('hsc.hsc-admission.view');
        if ($request->ajax()) {
            $data = HscAdmission::where('branch_id', auth()->user()->branch_id)->orderBy('id', 'desc'); // Add this line to order records
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
        $shifts = Shift::select('id', 'shift_name')->get();
        // $sections = Section::select('id', 'section_name')->get();
        $sections = ClassSection::where('student_class_id', 13)->get();
        return view("pages.hsc.admission.index",compact('shifts', 'sections'));
    }

    public function show($id){
        $this->authorize('hsc.hsc-admission.show');
        $applicant = HscAdmission::find($id);
     
        return view("pages.hsc.admission.show", compact('applicant'));
    }
    public function print($id){
        $applicant = HscAdmission::find($id);
        return view("pages.hsc.admission.print", compact('applicant'));
    }
    

    public function science()
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_common = GroupSubject::where('group_id', 1)->where('is_common', 1)->get();
        $group_elective = GroupSubject::where('group_id', 1)->where('is_common', 0)->where('type', GroupSubject::ELECTIVE)->get();
        $group_optional = GroupSubject::where('group_id', 1)->where('type', GroupSubject::OPTIONAL)->get();
     
        $occupations = Occupation::pluck('name', 'id');
        $guardian_relations = GuardianRelation::pluck('name', 'id');
        $divisions = Division::all();
        $selectedDivision = 1;
        $selectedDistrict = 0;
        $selectedUpazila = 0;
        $selectedUnion = 0;
        $branches = Branch::select('id','branch_name','address','contact_info')->get(); 
        
        return view("pages.hsc.admission.science", compact('selectedDivision','selectedDistrict','selectedUpazila','selectedUnion','divisions','occupations','guardian_relations','compulsory_subjects', 'group_common', 'group_elective', 'group_optional', 'branches'));
    }



    public function store_science(Request $request)
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_commons = GroupSubject::where('group_id', 1)->where('is_common', 1)->get();
        
        $data = $request->validate([
            'branch_id' => 'nullable|string|max:255',
            'admission_roll' => 'nullable|string|max:255',
            'session_year' => 'nullable|string|max:4',
            'class_roll' => 'nullable|string|max:255',
            'merit_position' => 'nullable|string|max:255',
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'applicant_mobile' => 'nullable|string|max:20',
            'email' => 'nullable|string|max:255',
            'blood_group' => 'nullable|string|max:5',
            'nid' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'marital_status' => 'nullable|string|max:20',
            'gender' => 'nullable|string|max:10',
            'nationality' => 'nullable|string|max:100',
            'religion' => 'nullable|string|max:100',
            'profile_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'board_select' => 'nullable|string|max:100',
            'passing_year' => 'nullable|string|max:4',
            'institute_name' => 'nullable|string|max:255',
            'ssc_roll_num' => 'nullable|string|max:255',
            'ssc_reg_num' => 'nullable|string|max:255',
            'ssc_session' => 'nullable|string|max:255',
            'ssc_gpa' => 'nullable|string|max:255',
            'optional_subject' => 'nullable|string|max:10',

            'father_name' => 'nullable|string|max:255',
            'father_nid' => 'nullable|string|max:255',
            'father_dob' => 'nullable|date',
            'father_mobile' => 'nullable|string|max:20',
            'father_occupation' => 'nullable|string|max:255',
            'father_income' => 'nullable|string|max:20',

            'mother_name' => 'nullable|string|max:255',
            'mother_nid' => 'nullable|string|max:255',
            'mother_dob' => 'nullable|date',
            'mother_mobile' => 'nullable|string|max:20',
            'mother_occupation' => 'nullable|string|max:255',
            'mother_income' => 'nullable|string|max:20',

            'guardian_selection' => 'nullable|string|max:50',
            'guardian_name' => 'nullable|string|max:255',
            'guardian_occupation' => 'nullable|string|max:255',
            'guardian_mobile' => 'nullable|string|max:255',
            'guardian_relation' => 'nullable|string|max:255',
            'guardian_address' => 'nullable|string|max:255',

            'present_division_id' => 'nullable|string|max:100',
            'present_district_id' => 'nullable|string|max:100',
            'present_upazila_id' => 'nullable|string|max:100',
            'present_union_id' => 'nullable|string|max:100',
            'present_address' => 'nullable|string|max:100',

            'permanent_division_id' => 'nullable|string|max:100',
            'permanent_district_id' => 'nullable|string|max:100',
            'permanent_upazila_id' => 'nullable|string|max:100',
            'permanent_union_id' => 'nullable|string|max:100',
            'permanent_address' => 'nullable|string|max:100',


            'special_quata' => 'nullable|string|max:100',
            'community' => 'nullable|string|max:100',

            'group_payment' => 'nullable|string|max:50',
            'payment_from_account' => 'nullable|string|max:255',
            'payment_amount' => 'nullable|string|max:255',
            'payment_tnxid' => 'nullable|string|max:255',

            'hscgruop' => 'nullable|string|max:50',

            'marital_status' => 'nullable|string|max:50',
        ]);


        foreach ($compulsory_subjects as $main_key => $compulsory_subject) {
            $data['main_subject' . ($main_key + 1)] = $compulsory_subject->subject_id;
        }

        foreach ($group_commons as $group_common_key => $group_commons) {
            $data['elective_subject' . ($group_common_key + 1)] = $group_commons->subject_id;
        }
        $data['elective_subject3'] = $request->elective_subject;

        // dd($data, $request->all(), $compulsory_subjects);

        if ($request->hasFile('profile_image')) {
            $file = $request->file('profile_image');

            $firstName = $data['first_name'] ?? 'unknown';
            $sscRoll = $data['ssc_roll_num'] ?? uniqid();

            $default_name = Str::slug($firstName . '_' . $sscRoll);

            $file_name = $this->fileUploadService->upload($file, 'uploads/hsc-student-profile', '', $default_name);
            $data['profile_image'] = $file_name;
        }


        HscAdmission::create($data);

        // // Render HTML from Blade
        // $html = View::make('pages.hsc.admission.admission-form', compact('data'))->render();

        // // Generate PDF file name
        // $filename = Str::slug($data['first_name'] ?? 'student') . '-' . now()->format('YmdHis') . '.pdf';

        // // Ensure directory exists
        // $directory = storage_path('app/public/admissions');
        // if (!file_exists($directory)) {
        //     mkdir($directory, 0775, true);
        // }

        // // Save PDF to storage
        // $pdfPath = "{$directory}/{$filename}";
        // $mpdf = new Mpdf();
        // $mpdf->WriteHTML($html);
        // $mpdf->Output($pdfPath, \Mpdf\Output\Destination::FILE);

        // return response()->download($pdfPath);

        return redirect()->back()->with('success', 'Admission submitted successfully.');
    }


    public function arts()
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_elective = GroupSubject::where('group_id', 2)->where('is_common', 0)->where('type', GroupSubject::ELECTIVE)->get();
        $group_optional = GroupSubject::where('group_id', 2)->where('type', GroupSubject::OPTIONAL)->get();
     
        $occupations = Occupation::pluck('name', 'id');
        $guardian_relations = GuardianRelation::pluck('name', 'id');
        $divisions = Division::all();
        $selectedDivision = 1;
        $selectedDistrict = 0;
        $selectedUpazila = 0;
        $selectedUnion = 0;
        $branches = Branch::select('id','branch_name','address','contact_info')->get(); 
        // dd($compulsory_subjects, $group_elective, $group_optional, $occupations, $guardian_relations, $divisions, $selectedDivision, $selectedDistrict, $selectedUpazila, $selectedUnion, $branches);
        return view("pages.hsc.admission.arts", compact('selectedDivision','selectedDistrict','selectedUpazila','selectedUnion','divisions','occupations','guardian_relations','compulsory_subjects', 'group_elective', 'group_optional', 'branches'));
    }



    public function store_arts(Request $request)
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $data = $request->validate([
            'branch_id' => 'nullable|string|max:255',
            'admission_roll' => 'nullable|string|max:255',
            'session_year' => 'nullable|string|max:4',
            'class_roll' => 'nullable|string|max:255',
            'merit_position' => 'nullable|string|max:255',
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'applicant_mobile' => 'nullable|string|max:20',
            'email' => 'nullable|string|max:255',
            'blood_group' => 'nullable|string|max:5',
            'nid' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'marital_status' => 'nullable|string|max:20',
            'gender' => 'nullable|string|max:10',
            'nationality' => 'nullable|string|max:100',
            'religion' => 'nullable|string|max:100',
            'profile_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'board_select' => 'nullable|string|max:100',
            'passing_year' => 'nullable|string|max:4',
            'institute_name' => 'nullable|string|max:255',
            'ssc_roll_num' => 'nullable|string|max:255',
            'ssc_reg_num' => 'nullable|string|max:255',
            'ssc_session' => 'nullable|string|max:255',
            'ssc_gpa' => 'nullable|string|max:255',
            'optional_subject' => 'nullable|string|max:10',

            'father_name' => 'nullable|string|max:255',
            'father_nid' => 'nullable|string|max:255',
            'father_dob' => 'nullable|date',
            'father_mobile' => 'nullable|string|max:20',
            'father_occupation' => 'nullable|string|max:255',
            'father_income' => 'nullable|string|max:20',

            'mother_name' => 'nullable|string|max:255',
            'mother_nid' => 'nullable|string|max:255',
            'mother_dob' => 'nullable|date',
            'mother_mobile' => 'nullable|string|max:20',
            'mother_occupation' => 'nullable|string|max:255',
            'mother_income' => 'nullable|string|max:20',

            'guardian_selection' => 'nullable|string|max:50',
            'guardian_name' => 'nullable|string|max:255',
            'guardian_occupation' => 'nullable|string|max:255',
            'guardian_mobile' => 'nullable|string|max:255',
            'guardian_relation' => 'nullable|string|max:255',
            'guardian_address' => 'nullable|string|max:255',

            'present_division_id' => 'nullable|string|max:100',
            'present_district_id' => 'nullable|string|max:100',
            'present_upazila_id' => 'nullable|string|max:100',
            'present_union_id' => 'nullable|string|max:100',
            'present_address' => 'nullable|string|max:100',

            'permanent_division_id' => 'nullable|string|max:100',
            'permanent_district_id' => 'nullable|string|max:100',
            'permanent_upazila_id' => 'nullable|string|max:100',
            'permanent_union_id' => 'nullable|string|max:100',
            'permanent_address' => 'nullable|string|max:100',


            'special_quata' => 'nullable|string|max:100',
            'community' => 'nullable|string|max:100',

            'group_payment' => 'nullable|string|max:50',
            'payment_from_account' => 'nullable|string|max:255',
            'payment_amount' => 'nullable|string|max:255',
            'payment_tnxid' => 'nullable|string|max:255',


            'marital_status' => 'nullable|string|max:50',
        ]);

        $data['hscgruop'] = 'arts'; 

        foreach ($compulsory_subjects as $main_key => $compulsory_subject) {
            $data['main_subject' . ($main_key + 1)] = $compulsory_subject->subject_id;
        }

        foreach ($request->elective_subjects as $key => $value) {
            $data['elective_subject' . ($key + 1)] = $value;
        }

        // dd($request->all(), $data);

        if ($request->hasFile('profile_image')) {
            $file = $request->file('profile_image');

            $firstName = $data['first_name'] ?? 'unknown';
            $sscRoll = $data['ssc_roll_num'] ?? uniqid();

            $default_name = Str::slug($firstName . '_' . $sscRoll);

            $file_name = $this->fileUploadService->upload($file, 'uploads/hsc-student-profile', '', $default_name);
            $data['profile_image'] = $file_name;
        }

        HscAdmission::create($data);
        return redirect()->back()->with('success', 'Admission submitted successfully.');
    }



    public function commerce()
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_elective = GroupSubject::where('group_id', 3)->where('is_common', 0)->where('type', GroupSubject::ELECTIVE)->get();
        $group_optional = GroupSubject::where('group_id', 3)->where('type', GroupSubject::OPTIONAL)->get();
     
        $occupations = Occupation::pluck('name', 'id');
        $guardian_relations = GuardianRelation::pluck('name', 'id');
        $divisions = Division::all();
        $selectedDivision = 1;
        $selectedDistrict = 0;
        $selectedUpazila = 0;
        $selectedUnion = 0;
        $branches = Branch::select('id','branch_name','address','contact_info')->get(); 
        // dd($compulsory_subjects, $group_elective, $group_optional, $occupations, $guardian_relations, $divisions, $selectedDivision, $selectedDistrict, $selectedUpazila, $selectedUnion, $branches);
        return view("pages.hsc.admission.commerce", compact('selectedDivision','selectedDistrict','selectedUpazila','selectedUnion','divisions','occupations','guardian_relations','compulsory_subjects', 'group_elective', 'group_optional', 'branches'));
    }

    public function store_commerce(Request $request)
    {
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $data = $request->validate([
            'branch_id' => 'nullable|string|max:255',
            'admission_roll' => 'nullable|string|max:255',
            'session_year' => 'nullable|string|max:4',
            'class_roll' => 'nullable|string|max:255',
            'merit_position' => 'nullable|string|max:255',
            'first_name' => 'nullable|string|max:255',
            'last_name' => 'nullable|string|max:255',
            'applicant_mobile' => 'nullable|string|max:20',
            'email' => 'nullable|string|max:255',
            'blood_group' => 'nullable|string|max:5',
            'nid' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'marital_status' => 'nullable|string|max:20',
            'gender' => 'nullable|string|max:10',
            'nationality' => 'nullable|string|max:100',
            'religion' => 'nullable|string|max:100',
            'profile_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'board_select' => 'nullable|string|max:100',
            'passing_year' => 'nullable|string|max:4',
            'institute_name' => 'nullable|string|max:255',
            'ssc_roll_num' => 'nullable|string|max:255',
            'ssc_reg_num' => 'nullable|string|max:255',
            'ssc_session' => 'nullable|string|max:255',
            'ssc_gpa' => 'nullable|string|max:255',
            'optional_subject' => 'nullable|string|max:10',

            'father_name' => 'nullable|string|max:255',
            'father_nid' => 'nullable|string|max:255',
            'father_dob' => 'nullable|date',
            'father_mobile' => 'nullable|string|max:20',
            'father_occupation' => 'nullable|string|max:255',
            'father_income' => 'nullable|string|max:20',

            'mother_name' => 'nullable|string|max:255',
            'mother_nid' => 'nullable|string|max:255',
            'mother_dob' => 'nullable|date',
            'mother_mobile' => 'nullable|string|max:20',
            'mother_occupation' => 'nullable|string|max:255',
            'mother_income' => 'nullable|string|max:20',

            'guardian_selection' => 'nullable|string|max:50',
            'guardian_name' => 'nullable|string|max:255',
            'guardian_occupation' => 'nullable|string|max:255',
            'guardian_mobile' => 'nullable|string|max:255',
            'guardian_relation' => 'nullable|string|max:255',
            'guardian_address' => 'nullable|string|max:255',

            'present_division_id' => 'nullable|string|max:100',
            'present_district_id' => 'nullable|string|max:100',
            'present_upazila_id' => 'nullable|string|max:100',
            'present_union_id' => 'nullable|string|max:100',
            'present_address' => 'nullable|string|max:100',

            'permanent_division_id' => 'nullable|string|max:100',
            'permanent_district_id' => 'nullable|string|max:100',
            'permanent_upazila_id' => 'nullable|string|max:100',
            'permanent_union_id' => 'nullable|string|max:100',
            'permanent_address' => 'nullable|string|max:100',


            'special_quata' => 'nullable|string|max:100',
            'community' => 'nullable|string|max:100',

            'group_payment' => 'nullable|string|max:50',
            'payment_from_account' => 'nullable|string|max:255',
            'payment_amount' => 'nullable|string|max:255',
            'payment_tnxid' => 'nullable|string|max:255',


            'marital_status' => 'nullable|string|max:50',
        ]);

        $data['hscgruop'] = 'commerce'; 

        foreach ($compulsory_subjects as $main_key => $compulsory_subject) {
            $data['main_subject' . ($main_key + 1)] = $compulsory_subject->subject_id;
        }

        foreach ($request->elective_subjects as $key => $value) {
            $data['elective_subject' . ($key + 1)] = $value;
        }

        // dd($request->all(), $data);

        if ($request->hasFile('profile_image')) {
            $file = $request->file('profile_image');

            $firstName = $data['first_name'] ?? 'unknown';
            $sscRoll = $data['ssc_roll_num'] ?? uniqid();

            $default_name = Str::slug($firstName . '_' . $sscRoll);

            $file_name = $this->fileUploadService->upload($file, 'uploads/hsc-student-profile', '', $default_name);
            $data['profile_image'] = $file_name;
        }

        HscAdmission::create($data);
        return redirect()->back()->with('success', 'Admission submitted successfully.');
    }

    
    

    public function edit($id){
        $this->authorize('hsc.hsc-admission.edit');
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_common = GroupSubject::where('group_id', 1)->where('is_common', 1)->get();
        $group_elective = GroupSubject::where('group_id', 1)->where('is_common', 0)->where('type', GroupSubject::ELECTIVE)->get();
        $group_optional = GroupSubject::where('group_id', 1)->where('type', GroupSubject::OPTIONAL)->get();
        $applicant = HscAdmission::find($id);
        // dd($applicant);
        return view("pages.hsc.admission.edit",compact('applicant','compulsory_subjects', 'group_common', 'group_elective', 'group_optional'));
    }


    public function update(Request $request, $id)
    {
        $this->authorize('hsc.hsc-admission.edit');
        $compulsory_subjects = GroupSubject::where('type', GroupSubject::COMPULSORY)->get();
        $group_commons = GroupSubject::where('group_id', 1)->where('is_common', 1)->get();

        $data = $request->validate([
            'admission_roll' => 'nullable|string|max:255',
            'session_year' => 'nullable|string|max:4',
            'class_roll' => 'nullable|string|max:255',
            'merit_position' => 'nullable|string|max:255',
            'first_name' => 'nullable|string|max:255',
            'applicant_mobile' => 'nullable|string|max:20',
            'blood_group' => 'nullable|string|max:5',
            'nid' => 'nullable|string|max:255',
            'dob' => 'nullable|date',
            'marital_status' => 'nullable|string|max:20',
            'gender' => 'nullable|string|max:10',
            'nationality' => 'nullable|string|max:100',
            'religion' => 'nullable|string|max:100',
            'profile_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'board_select' => 'nullable|string|max:100',
            'passing_year' => 'nullable|string|max:4',
            'institute_name' => 'nullable|string|max:255',
            'ssc_roll_num' => 'nullable|string|max:255',
            'ssc_reg_num' => 'nullable|string|max:255',
            'ssc_session' => 'nullable|string|max:255',
            'ssc_gpa' => 'nullable|string|max:255',
            'optional_subject' => 'nullable|string|max:10',

            'father_name' => 'nullable|string|max:255',
            'father_nid' => 'nullable|string|max:255',
            'father_dob' => 'nullable|date',
            'father_mobile' => 'nullable|string|max:20',
            'father_occupation' => 'nullable|string|max:255',
            'father_income' => 'nullable|string|max:20',

            'mother_name' => 'nullable|string|max:255',
            'mother_nid' => 'nullable|string|max:255',
            'mother_dob' => 'nullable|date',
            'mother_mobile' => 'nullable|string|max:20',
            'mother_occupation' => 'nullable|string|max:255',
            'mother_income' => 'nullable|string|max:20',

            'guardian_selection' => 'nullable|string|max:50',
            'guardian_name' => 'nullable|string|max:255',
            'gardian_nid' => 'nullable|string|max:255',
            'guardian_mobile' => 'nullable|string|max:20',

            'village_present' => 'nullable|string|max:255',
            'post_present' => 'nullable|string|max:255',
            'police_present' => 'nullable|string|max:255',
            'district_present' => 'nullable|string|max:255',
            'postcode_present' => 'nullable|string|max:20',

            'same_as_present' => 'nullable|string|max:10',

            'village_permanent' => 'nullable|string|max:255',
            'post_permanent' => 'nullable|string|max:255',
            'police_permanent' => 'nullable|string|max:255',
            'district_permanent' => 'nullable|string|max:255',
            'postcode_permanent' => 'nullable|string|max:20',

            'special_quata' => 'nullable|string|max:100',
            'community' => 'nullable|string|max:100',

            'group_payment' => 'nullable|string|max:50',
            'payment_from_account' => 'nullable|string|max:255',
            'payment_amount' => 'nullable|string|max:255',
            'payment_tnxid' => 'nullable|string|max:255',

            'hscgruop' => 'nullable|string|max:50',

            'maritals_status' => 'nullable|string|max:50',
        ]);

        foreach ($compulsory_subjects as $main_key => $compulsory_subject) {
            $data['main_subject' . ($main_key + 1)] = $compulsory_subject->subject_id;
        }

        foreach ($group_commons as $group_common_key => $group_commons) {
            $data['elective_subject' . ($group_common_key + 1)] = $group_commons->subject_id;
        }
        $data['elective_subject3'] = $request->elective_subject;


        if ($request->hasFile('profile_image')) {
            $file = $request->file('profile_image');

            $firstName = $data['first_name'] ?? 'unknown';
            $sscRoll = $data['ssc_roll_num'] ?? uniqid();

            $default_name = Str::slug($firstName . '_' . $sscRoll);

            $file_name = $this->fileUploadService->upload($file, 'uploads/hsc-student-profile', '', $default_name);
            $data['profile_image'] = $file_name;
        }

        HscAdmission::where('id',$id)->update($data);
        return redirect()->route('hsc-admission.index')->with('success', 'Successfully updated.');
    }

    public function destroy($id){
        $this->authorize('hsc.hsc-admission.delete');

        $hsc = HscAdmission::find($id);
        try {
            $hsc->delete();
            return redirect()
                ->route('hsc-admission.index')
                ->with('success', 'HSC Applicant successfully deleted.');
        } catch (\Exception $e) {
            return redirect()
                ->route('hsc-admission.index')
                ->with('error', 'Failed to delete HSC Applicant.');
        }
    }
}
