<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Event;
use App\Models\Notification;
use Carbon\Carbon; // Add this line
use Illuminate\Support\Facades\Auth; 
use App\Models\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class EventsController extends Controller
{
    public function index()
    {
        // Retrieve events and order them by event_date in descending order (latest first)
        $events = Event::orderBy('event_date', 'desc')->get();
        
        // Retrieve all clients
        $clients = Client::all();
        
        // Return the view with the sorted events and clients
        return view('admin.events.index', compact('events', 'clients'));
    }
    

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'client_name' => 'nullable|string|max:255',
            'event_date' => 'required|date',
            'event_time' => 'required|date_format:H:i',
        ]);

        $event = Event::create($request->all());

        // Create a new notification
        $clientUser = DB::table('users')->where('client_id', $request->client_name)->first();
        $notification = Notification::create([
            'title' => "A New Event Created",
            'body' => 'Event:- '.$request->title,
            'send_at' => now(), // Current date and time
            'sent' => $request->input('sent', false), // Default to false if not provided
            'url' => 'client.events.index', // Example route for redirection
            'from_id' => Auth::id(), // Authenticated user's ID
            'to_id' => $clientUser->id, // Client ID for to_id
        ]);

     // Send an email to the client user
        if ($clientUser && $clientUser->email) {
            $data = [
                'title' => $request->title,
                'description' => $request->description,
                'event_date' => $request->event_date,
                'event_time' => $request->event_time,
                'client_name' => $clientUser->name,
            ];

            Mail::send([], [], function ($message) use ($clientUser, $data) {
                $message->to($clientUser->email)
                        ->subject('New Event Created: ' . $data['title'])
                        ->html("
                            <h1>New Event Created</h1>
                            <p>Dear {$clientUser->name},</p>
                            <p>A new event has been created for you:</p>
                            <ul>
                                <li><strong>Title:</strong> {$data['title']}</li>
                                <li><strong>Description:</strong> {$data['description']}</li>
                                <li><strong>Date:</strong> {$data['event_date']}</li>
                                <li><strong>Time:</strong> {$data['event_time']}</li>
                            </ul>
                            <p>Please login to view more details.</p>
                        ");
            });
        }

        return redirect()->route('events.index')->with('success', 'Event added successfully!');
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:events,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'client_name' => 'nullable|string|max:255',
            'event_date' => 'required|date',
            'event_time' => 'required|date_format:H:i',
        ]);

        $event = Event::findOrFail($request->id);
        $event->update($request->all());

        return redirect()->route('events.index')->with('success', 'Event updated successfully!');
    }

    public function events()
    {
        $events = Event::all();
        $eventsFormatted = [];

        foreach ($events as $event) {
            $eventsFormatted[] = [
                'id' => $event->id,
                'title' => $event->title,
                'start' => $event->event_date . 'T' . $event->event_time,
                'description' => $event->description,
                'client_name' => $event->client_name,
            ];
        }

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

    public function markAsRead($id)
    {
        // Update the notification's sent status to 1
        DB::table('notifications')->where('id', $id)->update(['sent' => 1]);

        // Optionally, you can return a success response
        return response()->json(['status' => 'success', 'message' => 'Notification marked as read']);
    }

   
}
