<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Invoice;
use App\Traits\Model\Basic;
use Carbon\Carbon;
use Illuminate\Support\Str;

class Invoices
{
    use Basic;

    public static function getInvoiceHtml($id)
    {
        $invoice = self::get($id, ['order.customer', 'order.delivery_address', 'order.detail']);
        $order = $invoice->order;
        $customer = $order->customer;
        unset($invoice->order, $order->customer);
        $data = [
            'invoice' => $invoice->toArray(),
            'order' => $order->toArray(),
            'customer' => $customer->toArray(),
        ];

        return view('Shop.Invoices.mail', $data)->render();
    }

    public static function getByUUID($uuid)
    {
        return Invoice::byUUID($uuid)->first();
    }

    public static function saveInvoice($orderId, $data)
    {
        $data['order_id'] = $orderId;

        return self::store($data);
    }

    public static function countByMonth()
    {
        $start = Carbon::now()->beginOfMonth();

        return Invoice::where('created_at', '>', $start);
    }

    public static function create($data)
    {
        InvoiceStats::increase($data['total_taxed']);
        $data['uuid'] = Str::uuid()->toString();

        return Invoice::create($data);
    }

    public static function delete($id)
    {
        $invoice = self::get($id);
        InvoiceStats::decrease($invoice->total_priced);

        return Invoice::destroy($id);
    }

    public static function getNewRef()
    {
        $ref = date('ymd').'00000';
        $lastRef = Invoice::orderBy('id', 'desc')->first();

        return $lastRef ? $lastRef->ref + 1 : $ref + 1;
    }

    public static function getStatus($id)
    {
        return self::statuses()[$id] ?? false;
    }

    public static function statuses()
    {
        return ['En attente', 'Paiement partiel', 'Soldée', 'Paiement rejeté'];
    }

    public static function getModel()
    {
        return Invoice::query();
    }
}
