<?php

namespace App\Http\Controllers;

use App\Models\UserProfile;
use App\Models\Agenda;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AgendaController extends Controller
{
    public function __construct()
    {
        $this->middleware('checkStaff');
    }
    public function create_agend(Request $request, $id)
    {
        try {
            if (!Auth::check()) {
                return response()->json(['message' => 'Unauthorized'], 401);
            }

            $usrid = UserProfile::find($id);

            $validatedData = $request->validate([
                'agenda_name' => 'required|string',
                'with_klien' => 'nullable|integer',
                'start_time' => 'required|date',
                'end_time' => 'required|date',
                'participants' => 'nullable|array',
            ]);

            $validatedData['user_id_creator'] = $usrid->id;
            if (isset($validatedData['with_klien'])) {
                $klien = UserProfile::find($validatedData['with_klien']);
                if (!$klien) {
                    return response()->json(['message' => 'Klien not found'], 404);
                }
            }
            if (empty($validatedData['participants'])) {
                $validatedData['participants'] = json_encode(['everyone']);
            } else {
                $participants = [];
                foreach ($validatedData['participants'] as $id) {
                    $user = UserProfile::find($id);
                    if ($user) {
                        $participants[] = $user->id;
                    }
                }
                $validatedData['participants'] = empty($participants) ? json_encode(['everyone']) : json_encode($participants);
            }

            $agenda = Agenda::create($validatedData);

            return response()->json(['message' => 'Agenda created successfully', 'data' => $agenda], 201);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to create agenda', 'error' => $e->getMessage()], 500);
        }
    }

    public function update_agend(Request $request, $id)
    {
        try {
            Auth::check();

            $agenda = Agenda::findOrFail($id);

            if (!$agenda) {
                return response()->json(['message' => 'Agenda not found'], 404);
            }

            $validatedData = $request->validate([
                'agenda_name' => 'string',
                'with_klien' => 'nullable|integer',
                'start_time' => 'date',
                'end_time' => 'date',
                'participants' => 'nullable|array',
            ]);
            if (isset($validatedData['with_klien'])) {
                $klien = UserProfile::find($validatedData['with_klien']);
                if (!$klien) {
                    return response()->json(['message' => 'Klien not found'], 404);
                }
            }
            if (isset($validatedData['participants'])) {
                $participants = [];
                foreach ($validatedData['participants'] as $id) {
                    $user = UserProfile::find($id);
                    if ($user) {
                        $participants[] = $user->id;
                    }
                }
                $validatedData['participants'] = empty($participants) ? json_encode(['everyone']) : json_encode($participants);
            }

            $agenda->update($validatedData);

            return response()->json(['message' => 'Agenda updated successfully', 'data' => $agenda], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to update agenda', 'error' => $e->getMessage()], 500);
        }
    }

    public function delete_agend($id)
    {
        try {
            Auth::check();

            $agenda = Agenda::findOrFail($id);

            if (!$agenda) {
                return response()->json(['message' => 'Agenda not found'], 404);
            }

            $agenda->delete();

            return response()->json(['message' => 'Agenda deleted successfully']);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to delete agenda', 'error' => $e->getMessage()], 500);
        }
    }

    public function get_all_agend()
    {
        $agendas = Agenda::all();

        return response()->json(['data' => $agendas], 200);
    }

    public function get_dt_partic($id)
    {
        try {
            // Mengambil semua agenda yang memiliki ID peserta tertentu dalam kolom participants
            $agendas = Agenda::whereJsonContains('participants', (int) $id)->get();

            // Mengembalikan data agenda sebagai respons JSON
            return response()->json(['data' => $agendas], 200);
        } catch (\Exception $e) {
            // Mengembalikan pesan kesalahan jika terjadi masalah
            return response()->json(['message' => 'Failed to retrieve agendas', 'error' => $e->getMessage()], 500);
        }
    }
}