<?php

// Controller: SmsTemplateController.php
namespace App\Http\Controllers;

use App\Models\SmsTemplate;
use App\Models\SmsScheduled;
use App\Models\Category;
use App\Models\User;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class SmsTemplateController extends Controller
{
    public function index()
    {
        return view('sms.index');
    }

    public function getTemplatesJson(Request $request)
    {
        $templates = SmsTemplate::with('creator:id,name')->latest()->get();

        $data = $templates->map(function($template) {
            return [
                'id' => $template->id,
                'name' => $template->name,
                'content' => $template->content,
                'character_count' => strlen($template->content),
                'created_at' => $template->created_at->format('d/m/Y H:i'),
                'creator' => $template->creator->name ?? 'N/A'
            ];
        });

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

    public function store(Request $request)
    {
        $request->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string|max:160',
            'recipients' => 'required|array|min:1',
            'send_now' => 'required|boolean',
            'scheduled_at' => 'required_if:send_now,false|date|after:now',
        ]);

        $template = SmsTemplate::create([
            'name' => $request->subject,
            'content' => $request->message,
            'created_by' => Auth::id(),
        ]);

        $recipients = User::whereHas('categories', function ($query) use ($request) {
            $query->whereIn('categories.id', $request->recipients);
        })->get();

        if ($request->send_now) {
            $this->sendSmsNow($template, $recipients);
            $message = 'Template creato e SMS inviato a ' . $recipients->count() . ' destinatari!';
        } else {
            $this->scheduleSms($template, $recipients, $request->scheduled_at);
            $scheduledDate = Carbon::parse($request->scheduled_at)->format('d/m/Y H:i');
            $message = 'Template creato e SMS programmato per ' . $scheduledDate;
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'template' => [
                'id' => $template->id,
                'name' => $template->name,
                'content' => $template->content,
                'character_count' => strlen($template->content),
                'created_at' => $template->created_at->format('d/m/Y H:i'),
                'creator' => Auth::user()->name
            ]
        ]);
    }

    public function destroy($id)
    {
        $template = SmsTemplate::findOrFail($id);
        $template->delete();

        return response()->json([
            'success' => true,
            'message' => 'Template eliminato con successo!'
        ]);
    }

    public function getCategories()
    {
        $categories = Category::with('users')->get()->map(function($category) {
            return [
                'id' => $category->id,
                'name' => $category->name,
                'users_count' => $category->users->count()
            ];
        });

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

    public function getTemplate($id)
    {
        $template = SmsTemplate::findOrFail($id);

        return response()->json([
            'id' => $template->id,
            'name' => $template->name,
            'content' => $template->content
        ]);
    }

    private function sendSmsNow($template, $recipients)
    {
        foreach ($recipients as $recipient) {
            if ($recipient->phone) {
                Log::info("SMS sent to {$recipient->name} ({$recipient->phone}): {$template->content}");
            }
        }
    }

    private function scheduleSms($template, $recipients, $scheduledAt)
    {
        $scheduled = SmsScheduled::create([
            'template_id' => $template->id,
            'content' => $template->content,
            'scheduled_at' => Carbon::parse($scheduledAt),
            'status' => 'scheduled',
            'created_by' => Auth::id(),
        ]);

        $scheduled->recipients()->attach($recipients->pluck('id'));
    }
}
