<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\AsaMeeting;
use App\Models\AsaMeetingAttendee;
use App\Models\User;
use App\Notifications\AsaMeeting as NotificationsAsaMeeting;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Throwable;

class AsaMeetingController extends Controller
{
    public function show(Request $request, string $employee_id){
        
        DB::enableQueryLog();
        
        $meetings = DB::select('
            SELECT am.id, am.meeting_title, am.start_datetime, am.end_datetime, am.color, am.employee_id, am.room_id
            FROM asa_meetings am
            LEFT JOIN asa_meeting_attendees ama ON am.id = ama.meeting_id
            WHERE am.employee_id = ? AND am.enabled = 1
        ', [$employee_id]);

        // dd(DB::getQueryLog());
        
        $meetingsWithAttendees = [];
    
        foreach ($meetings as $meeting) {
            if (!isset($meetingsWithAttendees[$meeting->id])) {

                $attendeesData = [];
                
                DB::enableQueryLog();

                $attendees = DB::select('SELECT ama.employee_id, epp.attachment, CONCAT(e.firstname, " ", e.lastname) as fullname, ama.status
                FROM asa_meeting_attendees ama 
                LEFT JOIN employee_profile_pictures epp ON ama.employee_id = epp.employee_id
                LEFT JOIN employees e ON ama.employee_id = e.employee_id
                WHERE ama.meeting_id = ?', [$meeting->id]);

                // dd(DB::getQueryLog());

                foreach($attendees as $attendee){
                    if(!in_array($attendee->employee_id, $attendeesData)){
                        $attendeesData['employee_id'][] = $attendee->employee_id;
                        $attendeesData['attachment'][] = $attendee->attachment == null ? '' : asset('storage/employee-profile/' . $attendee->attachment);
                        $attendeesData['fullname'][] = $attendee->fullname;
                        $attendeesData['status'][] = $attendee->status;
                    }
                }

                $meetingsWithAttendees[$meeting->id] = [
                    'id' => $meeting->id,
                    'employee_id' => $meeting->employee_id,
                    'meeting_title' => $meeting->meeting_title,
                    'start_datetime' => $meeting->start_datetime,
                    'end_datetime' => $meeting->end_datetime,
                    'room_id' => $meeting->room_id,
                    'color' => $meeting->color,
                    'employee_invited' => $attendeesData['employee_id'],
                    'attendees' => $attendeesData,
                ];
            }
            
            // dd($attendeesData['employee_id']);
            if ($meeting->employee_id !== null) {
                $meetingsWithAttendees[$meeting->id]['employee_invited'][] = $meeting->employee_id;
            }
        }

        foreach ($meetingsWithAttendees as &$meeting) {
            $meeting['employee_invited'] = json_encode($meeting['employee_invited']);
        }

        // dd($meeting);

        $meetingsAttendee = DB::select('
            SELECT ama.id as attendee_id, am.employee_id, am.id as meeting_id, am.meeting_title, am.start_datetime, am.end_datetime, am.color, am.room_id
            FROM asa_meeting_attendees ama
            LEFT JOIN asa_meetings am ON ama.meeting_id = am.id
            WHERE ama.employee_id = ? AND ama.status != 99 AND ama.status != 0
        ', [$employee_id]);

        $meetingsData = [];

        foreach ($meetingsAttendee as $record) {
    
            if (!isset($meetingsData[$record->meeting_id])) {
                $attendeesData = [];
                
                $attendees = DB::select('SELECT ama.employee_id, epp.attachment, CONCAT(e.firstname, " ", e.lastname) as fullname, ama.status
                FROM asa_meeting_attendees ama 
                LEFT JOIN employee_profile_pictures epp ON ama.employee_id = epp.employee_id
                LEFT JOIN employees e ON ama.employee_id = e.employee_id
                WHERE ama.meeting_id = ?', [$record->meeting_id]);
                
                foreach($attendees as $attendee){
                    if(!in_array($attendee->employee_id, $attendeesData)){
                        $attendeesData['employee_id'][] = $attendee->employee_id;
                        $attendeesData['attachment'][] = $attendee->attachment == null ? '' : asset('storage/employee-profile/' . $attendee->attachment);
                        $attendeesData['fullname'][] = $attendee->fullname;
                        $attendeesData['status'][] = $attendee->status;
                    }
                }

                $meetingsData[$record->meeting_id] = [
                    'meeting_id' => $record->meeting_id,
                    'employee_id' => $record->employee_id,
                    'meeting_title' => $record->meeting_title,
                    'start_datetime' => $record->start_datetime,
                    'end_datetime' => $record->end_datetime,
                    'room_id' => $record->room_id,
                    'color' => $record->color,
                    'employee_invited' => [],
                    'attendees' => $attendeesData,
                ];
            }
        }
        
        // dd($meetingsData);

        // foreach ($meetingsData as &$meeting) {
        //     $meeting['attendees'] = json_encode($meeting['attendees']);
        // }

        $meetingsData = array_values($meetingsData);
        $meetingsAttendee = array_values($meetingsAttendee);

        $data = [
            'meetingsWithAttendees' => $meetingsWithAttendees,
            'meetingsData' => $meetingsData
        ];

        // dd($data);
        
        return response()->json($data);
    }    

    public function getRoomAvailability(Request $request)
    {
        // dd($request->all());

        DB::enableQueryLog();

        $data = DB::select('SELECT `start_datetime`, `end_datetime` 
            FROM `asa_meetings` 
            WHERE `room_id` = ? AND DATE(`start_datetime`) = ?', 
            [$request->room_id, $request->date]);

        // dd(DB::getQueryLog());

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

    public function getMeetingInvitation(Request $request)
    {                                                                                                                                       
        $user = Auth::user();

        if($user->roles[0]->group_id == 1){
            $employee_id = 'admin';
        } else {
            $employee_id = $user->employees->employee_id;
        }

        DB::enableQueryLog();

        // Define the current page and items per page
        $currentPage = Paginator::resolveCurrentPage();
        $perPage = 15; // Number of items per page

        // Build the query using Query Builder
        $query = DB::table('asa_meetings as am')
            ->join('asa_meeting_attendees as ama', 'am.id', '=', 'ama.meeting_id')
            ->select('ama.id', 'am.meeting_title', 'am.room_id', 'am.start_datetime', 'am.end_datetime', 'ama.status')
            ->where('ama.employee_id', $employee_id)
            ->where('am.enabled', 1)
            ->where('ama.enabled', 1);

        // Paginate the results
        $data = $query->paginate($perPage, ['*'], 'page', $currentPage);

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

    public function store(Request $request)
    {
        // dd($request->all());
        $user = Auth::user();

        // Validate request
        $validatedData = $request->validate([
            'title' => 'required|string|max:255',
            'employee_invited' => 'required|array',
            'start_time' => 'required',
            'end_time' => 'required',
        ]);

        // Prepare and insert meeting data
        // dd($request->color);

        $meeting = AsaMeeting::create([
            'meeting_title' => $validatedData['title'],
            'employee_id' => $user->employees->employee_id,
            'start_datetime' => $request['start_datetime'].' '.$validatedData['start_time'],
            'end_datetime' => $request['start_datetime'].' '.$validatedData['end_time'],
            'color' => $request->color,
            'room_id' => $request->room_id,
            'date_created' => now(),
            'update_at' => now(),
            'fullname' => $user->first_name, ' ', $user->last_name
        ]);

        // dd($meeting);

        // Find the employees
        $employees = User::whereIn('employee_id', $validatedData['employee_invited'])->get();

        // Send notifications to each employee
        foreach ($employees as $employee) {
            try {
                if ($employee->email != '') {
                    Notification::send($employee, new NotificationsAsaMeeting($meeting));
                }
            } catch (\Throwable $e) {
                // Log it for debugging instead of silently ignoring
                \Log::error('Meeting notification failed for employee ' . $employee->employee_id . ': ' . $e->getMessage());
            }

            AsaMeetingAttendee::create([
                'meeting_id' => $meeting->id,
                'employee_id' => $employee->employee_id,
                'date_sent' => now(),
            ]);
        }

        return response()->json(['meeting_id' => $meeting->id]);
    }


    public function update(Request $request, int $id){
        $asa_meeting = AsaMeeting::findOrFail($id);

        // $asa_meeting->
    }

    public function updateMeetingConfirmation(Request $request, int $id){

        $asa_meeting = AsaMeetingAttendee::findOrFail($id);
        
        DB::connection()->beginTransaction();

        try {

            $asa_meeting->fill($request->all());
            $asa_meeting->save();

            $asa_meeting->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $asa_meeting,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }

    }

    public function destroy(string $id)
    {
        // Start a database transaction
        DB::connection()->beginTransaction();

        try {
            // Find the record
            $data = AsaMeeting::find($id);
            
            // Check if the record was found
            if (!$data) {
                DB::connection()->rollBack();
                return response()->json(['messages' => 'No data found.'], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            // Update the record
            $data->update(['enabled' => 0]);

            // Touch the record to update the timestamp
            // $data->save();

            $data->touch();

            // Commit the transaction
            DB::connection()->commit();

            // Return a success response
            return response()->json([
                'status'  => true,
                'message' => 'Record successfully updated.',
                'data'    => $data,
            ]);

        } catch (Throwable $e) {
            // Rollback the transaction if there's an error
            DB::connection()->rollBack();

            // Return an error response
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }
    
}
