<?php

namespace App\Http\Controllers;

use App\Models\Meeting;
use App\Models\Client;
use Illuminate\Http\Request;

class MeetingController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,client_id',
            'title' => 'required|string|max:255',
            'meeting_date' => 'required|date',
            'meeting_time' => 'required',
            'location' => 'nullable|string|max:255',
        ]);

        // Create meeting_datetime from date and time
        $meetingDateTime = $request->meeting_date . ' ' . $request->meeting_time;
        $meetingId = 'MTG_' . rand(10000, 99999);

        // Process advanced reminders
        $reminderLabels = [
            'r1' => '১ দিন আগে',
            'r2' => '৩ ঘন্টা আগে', 
            'r3' => '৩০ মিনিট আগে',
            'r4' => '১০ মিনিট আগে'
        ];
        
        $selectedReminders = [];
        foreach ($reminderLabels as $key => $label) {
            if ($request->has($key) && $request->get($key) == '1') {
                $selectedReminders[] = $label;
            }
        }
        
        // Default reminders if none selected
        if (empty($selectedReminders)) {
            $selectedReminders = ['১ দিন আগে', '৩ ঘন্টা আগে', '৩০ মিনিট আগে'];
        }

        Meeting::create([
            'meeting_id' => $meetingId,
            'client_id' => $request->client_id,
            'title' => $request->title,
            'meeting_datetime' => $meetingDateTime,
            'location' => $request->location ?? 'Google Meet',
            'reminders' => $selectedReminders
        ]);

        return redirect()->route('dashboard')->with('success', 'Meeting scheduled successfully!');
    }

    public function index()
    {
        $meetings = Meeting::with('client')->orderBy('meeting_datetime', 'desc')->get();
        return view('meetings', compact('meetings'));
    }

    public function destroy($id)
    {
        $meeting = Meeting::findOrFail($id);
        $meeting->delete();
        
        return response()->json(['success' => true]);
    }
}
