<?php

namespace App\Livewire\Tickets;

use App\Models\Tickets;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Rating extends Component
{
    public $ticket_id;
    public $rating = 0;
    public $canRate = false;
    public $public_hash = null;

    public function mount($ticket_id, $public_hash = null)
    {
        $this->ticket_id = $ticket_id;
        $this->public_hash = $public_hash;

        $ticket = Tickets::where('id', '=', $this->ticket_id)->first();

        if ($ticket) {
            $this->rating = (int) ($ticket->rating ?? 0);

            // Customers and employees can rate their own tickets
            if (Auth::check()) {
                $user = Auth::user();
                $this->canRate = $ticket->user_id == $user->id;
            }
            // Guests can rate their tickets if viewing via public hash
            elseif ($this->public_hash && $ticket->public_hash === $this->public_hash) {
                // Verify this is a guest ticket (user_id is 0 or null)
                if ($ticket->user_id == '0' || $ticket->user_id === null) {
                    $this->canRate = true;
                }
            }
        }
    }

    public function setRating($rating)
    {
        if (!$this->canRate) {
            return;
        }

        $this->rating = $rating;

        $ticket = Tickets::where('id', '=', $this->ticket_id)->first();

        if ($ticket) {
            // Additional verification for guest tickets
            if (!Auth::check() && $this->public_hash) {
                // Verify the hash matches before allowing guest to rate
                if ($ticket->public_hash !== $this->public_hash ||
                    ($ticket->user_id != '0' && $ticket->user_id !== null)) {
                    return;
                }
            }

            $ticket->rating = $rating;
            $ticket->save();
        }
    }

    public function render()
    {
        return view('livewire.tickets.rating');
    }
}
