<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use App\Http\Middleware\TenantMiddleware;
use App\Models\SmsTemplate;
use App\Models\SmsScheduled;
use App\Models\Category;
use App\Models\Member;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class SmsComunications extends Component
{
    public $records, $subject, $message, $selectedRecipients = [], $scheduledDateTime, $sendNow = true;
    public $dataId, $update = false, $add = false;
    public $members = [];

    protected $rules = [
        'subject' => 'required|string|max:255',
        'message' => 'required|string|max:160',
        'selectedRecipients' => 'required|array|min:1',
        'scheduledDateTime' => 'required_if:sendNow,false|date|after:now',
    ];

    protected $messages = [
        'subject.required' => 'L\'oggetto è obbligatorio',
        'message.required' => 'Il messaggio è obbligatorio',
        'message.max' => 'Il messaggio non può superare 160 caratteri',
        'selectedRecipients.required' => 'Seleziona almeno un gruppo di destinatari',
        'scheduledDateTime.required_if' => 'La data di programmazione è obbligatoria',
        'scheduledDateTime.after' => 'La data di programmazione deve essere futura',
    ];

    public $sortField = 'name';
    public $sortAsc = true;

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    public function sortBy($field)
    {
        if($this->sortField === $field) {
            $this->sortAsc = ! $this->sortAsc;
        } else {
            $this->sortAsc = true;
        }

        $this->sortField = $field;
    }

    public function resetFields()
    {
        $this->subject = '';
        $this->message = '';
        $this->selectedRecipients = [];
        $this->sendNow = true;
        $this->scheduledDateTime = now()->addHour()->format('Y-m-d\TH:i');
        $this->emit('load-data-table');
    }

    public function mount()
    {
        if(Auth::user()->level != env('LEVEL_ADMIN', 0))
            return redirect()->to('/dashboard');

        $this->members = Member::select('id', 'last_name', 'email')->get();
        $this->scheduledDateTime = now()->addHour()->format('Y-m-d\TH:i');
    }

    public function render()
    {
        $this->records = SmsTemplate::orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->get();
        return view('livewire.sms_comunications');
    }

    public function add()
    {
        $this->resetFields();
        $this->add = true;
        $this->update = false;
    }

    public function store()
    {
        $this->validate();

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

            $recipients = User::whereIn('id', $this->selectedRecipients)->get();

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

            $this->resetFields();
            $this->add = false;
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function edit($id)
    {
        try {
            $template = SmsTemplate::findOrFail($id);
            if (!$template) {
                session()->flash('error', 'Template SMS non trovato');
            } else {
                $this->subject = $template->name;
                $this->message = $template->content;
                $this->dataId = $template->id;
                $this->update = true;
                $this->add = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function update()
    {
        $this->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string|max:160',
        ]);

        try {
            SmsTemplate::whereId($this->dataId)->update([
                'name' => $this->subject,
                'content' => $this->message,
            ]);
            session()->flash('success', 'Template SMS aggiornato');
            $this->resetFields();
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    public function cancel()
    {
        $this->add = false;
        $this->update = false;
        $this->resetFields();
    }

    public function sendTemplate($id)
    {
        try {
            $template = SmsTemplate::findOrFail($id);
            $this->subject = $template->name;
            $this->message = $template->content;
            $this->add = true;
            $this->update = false;
        } catch (\Exception $ex) {
            session()->flash('error', 'Errore (' . $ex->getMessage() . ')');
        }
    }

    private function sendSmsNow($template, $recipients)
    {
        // Simple SMS sending logic
        foreach ($recipients as $recipient) {
            if ($recipient->phone) {
                // Here you would integrate with your SMS provider
                Log::info("SMS sent to {$recipient->name} ({$recipient->phone}): {$template->content}");
            }
        }
    }

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

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

        Log::info("SMS scheduled for {$this->scheduledDateTime} to {$recipients->count()} recipients: {$template->content}");
    }
}
