<?php

namespace App\Http\Controllers\Hostel;

use App\Constants\Status;
use Illuminate\Http\Request;
use App\Models\Academic\Group;
use App\Models\Academic\Shift;
use App\Services\HostelService;
use App\Models\Academic\Section;
use App\Models\Hostel\HostelRoom;
use App\Models\Accounting\FeeType;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Hostel\StudentHostel;
use App\Models\Academic\StudentClass;
use App\Models\Accounting\StudentFee;
use App\Models\Hostel\Hostel;

class AssignHostelRoomController extends Controller
{

    public function index(Request $request, HostelService $hostelService)
    {

        $students = $hostelService->get($request->query());
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $groups = Group::pluck('group_name', 'id');
        $shifts = Shift::pluck('shift_name', 'id');
        $sections = Section::pluck('section_name', 'id');

        $hostels = Hostel::pluck('name', 'id');

        // $hostel_rooms = HostelRoom::with(['hostel', 'roomType', 'hostelFloor'])
        //     ->leftJoin('student_hostels', function ($join) {
        //         $join->on('hostel_rooms.id', '=', 'student_hostels.hostel_room_id')
        //             ->where('student_hostels.status', '=', Status::ASSIGNED);
        //     })
        //     ->select('hostel_rooms.*', DB::raw('COUNT(student_hostels.id) as assigned_beds'))
        //     ->groupBy('hostel_rooms.id')
        //     ->get()
        //     ->map(function ($room) {
        //         $room->assigned_beds = $room->assigned_beds ?? 0;
        //         $room->empty_beds = $room->no_of_bed - $room->assigned_beds;
        //         return $room;
        //     });

            // dd($students);

        return view('pages.hostels.assign-room.index', compact('students', 'studentClasses', 'groups', 'shifts', 'sections', 'hostels'));
    }

    public function assignHostelRoom(Request $request)
    {
        $request->validate([
            'student_id'   => 'required|exists:student_infos,id',
            'hostel_id'  => 'required|exists:hostels,id',
            'monthly_cost' => 'required|numeric|min:0',
        ]);

        // dd($request);
        $student_id = $request->input('student_id');
        $hostel_id = $request->input('hostel_id');
        $monthly_cost = $request->input('monthly_cost');

        if (empty($hostel_id)) {
            return response()->json([
                'success' => false,
                'message' => 'Please select a room!',
            ]);
        }

        // If monthly cost is 0 → remove transport
        if ((float) $request->monthly_cost == 0) {
            StudentHostel::where('student_id', $request->student_id)->delete();

            return response()->json([
                'success' => true,
                'message' => 'Hostel removed successfully'
            ]);
        }

        // Otherwise store or update
        StudentHostel::updateOrCreate(
            ['student_id' => $request->student_id],
            [
                'hostel_id'  => $request->hostel_id,
                'cost' => $request->monthly_cost,
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Hostel assigned successfully'
        ]);



        // $hostel_room = HostelRoom::with('roomType')->where('id', $hostel_room_id)->first();
        // $total_bed = $hostel_room->no_of_bed;
   
        // $assigned_bed = StudentHostel::where('hostel_room_id', $hostel_room_id)->count() ?? 0;
        // $available_bed = $total_bed - $assigned_bed;

        // $check_exist = StudentHostel::where('student_id', $student_id)
        //     ->exists();

        // if($check_exist){

        //     $available_bed += 1;
        // }

        // $hostelFeeTypes = FeeType::where('code', 'HOSTEL')->get();

        // if ($available_bed > 0 && !$check_exist) {
        //     // Store the data in your database
        //     StudentHostel::create([
        //         'student_id' => $student_id,
        //         'hostel_id' => $hostel_room->hostel_id,
        //         'hostel_floor_id' => $hostel_room->hostel_floor_id,
        //         'hostel_room_id' => $hostel_room_id,
        //         'room_type_id' => $hostel_room->roomType->id,
        //         'cost' => $hostel_room->roomType->cost_per_bed,
        //     ]);

        //     foreach ($hostelFeeTypes as $hostelFeeType) {
        //         StudentFee::create([
        //             'student_id' => $student_id,
        //             'fee_type_id' => $hostelFeeType->id,
        //             'month' => $hostelFeeType->month,
        //             'amount' => $hostel_room->roomType->cost_per_bed,
        //         ]);
        //     }

        //     return response()->json([
        //         'success' => true,
        //         'message' => 'Student hostel room assigned successfully!',
        //     ]);
        // } elseif ($available_bed > 0 && $check_exist) {
        //     StudentHostel::where('student_id', $student_id)->update([
        //         'hostel_id' => $hostel_room->hostel_id,
        //         'hostel_floor_id' => $hostel_room->hostel_floor_id,
        //         'hostel_room_id' => $hostel_room_id,
        //         'room_type_id' => $hostel_room->roomType->id,
        //         'cost' => $hostel_room->roomType->cost_per_bed,
        //     ]);

        //     foreach ($hostelFeeTypes as $hostelFeeType) {
        //         StudentFee::where('student_id', $student_id)
        //             ->where('fee_type_id', $hostelFeeType->id)
        //             ->update([
        //                 'amount' => $hostel_room->roomType->cost_per_bed,
        //             ]);
        //     }

        //     return response()->json([
        //         'success' => true,
        //         'message' => 'Student hostel room updated successfully!',
        //     ]);
        // } elseif ($available_bed <= 0) {

        //     return response()->json([
        //         'success' => false,
        //         'message' => 'No bed available in this room.Try different room!',
        //     ]);
        // } else {
        //     return response()->json([
        //         'success' => true,
        //         'error' => 'Something went wrong. Try Again!',
        //     ]);
        // }
    }

    public function searchHostelRooms(Request $request)
    {

        $hostel_rooms = HostelRoom::with(['hostel', 'roomType', 'hostelFloor'])
            ->leftJoin('student_hostels', function ($join) {
                $join->on('hostel_rooms.id', '=', 'student_hostels.hostel_room_id')
                    ->where('student_hostels.status', '=', Status::ASSIGNED);
            })
            ->select('hostel_rooms.*', DB::raw('COUNT(student_hostels.id) as assigned_beds'))
            ->where('hostel_rooms.room_name', $request->room_no)
            ->groupBy('hostel_rooms.id')
            ->get()
            ->map(function ($room) {
                $room->assigned_beds = $room->assigned_beds ?? 0;
                $room->empty_beds = $room->no_of_bed - $room->assigned_beds;
                return $room;
            });
        return response()->json($hostel_rooms);
    }


    public function listByHostel(Request $request)
    {

        $hostel_id = $request->hostel_id;

        $hostel_rooms = HostelRoom::with(['hostel', 'roomType', 'hostelFloor'])
            ->leftJoin('student_hostels', function ($join) {
                $join->on('hostel_rooms.id', '=', 'student_hostels.hostel_room_id')
                    ->where('student_hostels.status', '=', Status::ASSIGNED);
            })
            ->select('hostel_rooms.*', DB::raw('COUNT(student_hostels.id) as assigned_beds'))
            ->where('hostel_rooms.hostel_id', $hostel_id)
            ->groupBy('hostel_rooms.id')
            ->get()
            ->map(function ($room) {
                $room->assigned_beds = $room->assigned_beds ?? 0;
                $room->empty_beds = $room->no_of_bed - $room->assigned_beds;
                return $room;
            });
        return response()->json($hostel_rooms);
    }

    public function studentHostelRooms(Request $request)
    {

        $hostel_rooms = HostelRoom::with(['hostel', 'roomType', 'hostelFloor'])
            ->leftJoin('student_hostels', function ($join) {
                $join->on('hostel_rooms.id', '=', 'student_hostels.hostel_room_id')
                    ->where('student_hostels.status', '=', Status::ASSIGNED);
            })
            ->select('hostel_rooms.*', DB::raw('COUNT(student_hostels.id) as assigned_beds'))
            ->where('hostel_rooms.id', $request->hostel_room_id)
            ->groupBy('hostel_rooms.id')
            ->first();

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