<?php

namespace App\Repositories\Shop;

use App\Models\Shop\Order;
use App\Repositories\Core\DateStats;
use App\Repositories\Core\PDF;
use App\Traits\Model\Basic;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class Orders
{
    use Basic, DateStats;

    public static function view($uuid)
    {
        $data = self::getFullByUUID($uuid)->toArray();
        $data['payment_type'] = InvoicePayments::getPaymentType($data['payment_type']);
        $data['status'] = self::getStatus($data['status']);

        return $data;
    }

    public static function getLast($nb = 10)
    {
        return Order::with('customer')->orderBy('id', 'DESC')->take($nb)->get();
    }

    public static function getPdfByUUID($uuid)
    {
        return self::getPdf(self::getIdByUUID($uuid), 'commande-'.$uuid.'.pdf');
    }

    public static function getPdf($id, $file = 'order.pdf')
    {
        $data = [
            'order' => Orders::getFull($id),
        ];

        $customerId = Customers::getId();
        if ($customerId !== $data['order']['customer_id']) {
            return response()->view('errors.403');
        }

        return PDF::view('Shop.Orders.view', $data, $file);
    }

    public static function getFullByUUID($uuid)
    {
        return self::getByUUID($uuid, self::full());
    }

    public static function getFull($id)
    {
        return self::get($id, self::full());
    }

    public static function saveOrder($data)
    {
        $basket = $data['basket'];
        $invoice = $data['invoice'] ?? [];
        unset($data['basket'], $data['invoice']);
        $data += self::getSummaryOfBasket($basket);
        $order = self::store($data);
        $detail = $order ? OrderDetails::saveBasket($order->id, $basket['detail']) : false;
        $data = Arr::except($data, [
            'comment',
            'agree',
            'delivery_address_id',
            'sale_channel_id',
            'delivery_id',
            'delivery_type_id',
        ]);
        $invoice = $detail ? Invoices::saveInvoice($order->id, $data + $invoice) : false;

        return $invoice ? $order : false;
    }

    public static function getSummaryOfBasket($basket)
    {
        return [
            'total' => $basket['total'],
            'taxes' => $basket['taxes'],
            'total_taxed' => $basket['total_taxed'],
            'shipping' => $basket['shipping'],
            'total_shipped' => $basket['total_shipped'],
        ];
    }

    public static function edit($id)
    {
        return [
            'order' => self::get($id, [
                'customer',
                'invoice.address',
                'delivery',
                'delivery_address',
                'detail',
                'sale_channel',
            ])->toArray(),
            'statuses' => self::statuses(),
            'delivery_types' => DeliveryTypes::getOptions(),
            'payment_types' => self::paymentTypes(),
            'sale_channels' => SaleChannels::getOptions(),
        ];
    }

    public static function create($data)
    {
        OrderStats::increase();
        $data['uuid'] = Str::uuid()->toString();
        $data['ref'] = self::getNewRef();

        return Order::create($data);
    }

    public static function download($id)
    {
        dump($id);
        exit;
    }

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

    public static function getStatusBadge($id)
    {
        $label = self::getStatus($id);
        if ($label === false) {
            return '';
        }

        $classes = [
            0 => 'badge-warning',
            1 => 'badge-info',
            2 => 'badge-primary',
            3 => 'badge-success',
            4 => 'badge-danger',
        ];

        $class = $classes[$id] ?? 'badge-secondary';

        return '<span class="badge '.$class.'">'.$label.'</span>';
    }

    public static function getStatusByName($name)
    {
        $data = array_flip(self::statuses());

        return $data[$name] ?? '';
    }

    public static function statuses()
    {
        return ['En attente', 'Préparation', 'Expédié', 'Livré', 'Annulé'];
    }

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

    public static function paymentTypes()
    {
        return ['', 'CARTE BANCAIRE', 'CHEQUE', 'VIREMENT BANCAIRE'];
    }

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

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

    public static function full()
    {
        return ['customer', 'delivery', 'delivery_address', 'detail', 'invoice.address', 'sale_channel'];
    }

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