<?php

namespace App\Policies;

use App\Models\Invoice;
use App\Models\User;

class InvoicePolicy
{
    /**
     * Determine if the user can view any invoices.
     */
    public function viewAny(User $user): bool
    {
        return $user->hasRole('admin') || $user->hasRole('staff');
    }

    /**
     * Determine if the user can view the invoice.
     */
    public function view(User $user, Invoice $invoice): bool
    {
        // Admin and staff can view all
        if ($user->hasRole('admin') || $user->hasRole('staff')) {
            return true;
        }

        // Customers can only view their own invoices
        if ($user->hasRole('customer')) {
            return $invoice->customer_id === $user->id;
        }

        return false;
    }

    /**
     * Determine if the user can create invoices.
     */
    public function create(User $user): bool
    {
        return $user->hasRole('admin') || $user->hasRole('staff');
    }

    /**
     * Determine if the user can update the invoice.
     */
    public function update(User $user, Invoice $invoice): bool
    {
        // Only admin and staff can update
        if ($user->hasRole('admin') || $user->hasRole('staff')) {
            return true;
        }

        return false;
    }

    /**
     * Determine if the user can delete the invoice.
     */
    public function delete(User $user, Invoice $invoice): bool
    {
        // Only admin can delete
        return $user->hasRole('admin');
    }

    /**
     * Determine if the user can send the invoice.
     */
    public function send(User $user, Invoice $invoice): bool
    {
        return $user->hasRole('admin') || $user->hasRole('staff');
    }

    /**
     * Determine if the user can download the invoice PDF.
     */
    public function downloadPdf(User $user, Invoice $invoice): bool
    {
        return $this->view($user, $invoice);
    }
}
