<?php
/**
 * Order Item Object Eloquent model.
 * @version 27/10/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */

namespace Mtc\Shop\Order;

use Database\Factories\OrderItemsFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
use Mtc\Core\Admin\User;
use Mtc\Core\Permissions;
use Mtc\Plugins\Refunds\Classes\RefundItem;
use Mtc\Shop\Item\BelongsToItem;
use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Item\Size;
use Mtc\Shop\Order;
use Mtc\Shop\Assessment\Assessment;

/**
 * Order Item Object Eloquent model.
 * Implements functionality for managing Shop Basket Items
 *
 * @version 27/10/16
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
class Item extends Model
{
    use HasFactory;
    // Use trait that defines relationship to items
    use BelongsToItem;
    // Use trait that defines relationship to basket
    use BelongsToOrder;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'order_items';

    /**
     * @var array The attributes that are mass assignable.
     */
    protected $fillable = [
        'order_id',
        'item_id',
        'bundle_id',
        'prescription_item_id',
        'assessment_id',
        'item_name',
        'item_price',
        'item_price_exvat',
        'quantity',
        'recommended_quantity',
        'size',
        'PLU',
        'sizeid',
        'discount',
        'sale_item',
        'vat_deducatble',
        'price_paid',
        'price_paid_exvat',
        'approved',
        'clinic_checked',
        'reminder_date',
        'pharmacy_label_text',
        'has_requested_subscription',
        'has_requested_subscription_period',
    ];

    const ORDER_ITEM_AWAITING = 0;
    const ORDER_ITEM_APROVED = 1;
    const ORDER_ITEM_REJECTED = 2;
    const ORDER_ITEM_CLINICALLY_CHECKED = 3;

    public static $approved_statuses = [
        self::ORDER_ITEM_AWAITING => 'Awaiting',
        self::ORDER_ITEM_APROVED => 'Approved',
        self::ORDER_ITEM_REJECTED => 'Rejected',
        self::ORDER_ITEM_CLINICALLY_CHECKED => 'Clinically Checked',
    ];

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    public static function getMeta($order_item_id, $item_id) {
        return DB::table('order_items_meta')
            ->where('order_item_id', $order_item_id)
            ->where('item_id', $item_id)
            ->orderBy('id')
            ->get();
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function item()
    {
        return $this->belongsTo(\Mtc\Shop\Item::class);
    }

    public function prescription_item()
    {
        return $this->belongsTo(\Mtc\Plugins\NHS\Classes\PrescriptionItem::class);
    }

    public function item_size()
    {
        return $this->belongsTo(Size::class, 'sizeid');
    }

    public function archive_items()
    {
        return $this->hasMany(ArchiveItem::class);
    }

    /**
     * @return HasMany
     */
    public function shipmentItems(): hasMany
    {
        return $this->hasMany(ShipmentItem::class, 'order_item_id');
    }

    public function approval()
    {
        return $this->hasOne(\ApprovalLog::class, 'order_item_id');
    }

    public function bundle()
    {
        return $this->belongsTo(\MtcPharmacy\Bundles\Classes\Bundle::class);
    }

    public function assessment()
    {
        return $this->belongsTo(Assessment::class);
    }

    public function refund_items()
    {
        return $this->hasMany(RefundItem::class, 'order_item_id');
    }


    /**
     * Check if order Item can be approved by admin user
     *
     * @param Item $orderItem
     * @return bool
     */
    public static function orderItemCanBeApproved(Item $orderItem): bool
    {
        $item = $orderItem->item;

        if ($item->product_type === \Mtc\Shop\Item::TYPE_DOCTOR) {
            // Doctor approves item
            if (Permissions::can(Permissions::REVIEW_DOCTOR_ORDERS)) {
                return true;
            }
            // Pharmacist clinically checks approved item
            if (
                (int)$orderItem->approved === 1 &&
                Permissions::can(Permissions::CLINICALLY_CHECK_ORDER)
            ) {
                return true;
            }
        }

        // Pharmacist approves item
        if (
            $item->product_type === \Mtc\Shop\Item::TYPE_PHARMACY &&
            Permissions::can(Permissions::REVIEW_PHARMACY_ORDERS)
        ) {
            return true;
        }
        return false;
    }

    /**
     * Creates a copy of order item in order_archive_items table. Required as the admin in now able to edit order items
     */
    public function archive()
    {
        $order_item = $this->toArray();
        $order_item['order_item_id'] = $order_item['id'];
        ArchiveItem::query()->create($order_item);
    }


    public function getCustomersForLabels() : array
    {
        $customers = [];

        $assessment = $this->assessment;
        if ($assessment) {
            if ($assessment->customer_name && strlen($assessment->customer_name) > 1) {
                $customers[] = [
                    'name' => $assessment->customer_name,
                    'dob' => $assessment->customer_dob,
                    'age' => $assessment->getAge(),
                ];
            }
        }

        if (! $customers) {
            $customers[] = [
                'name' => $this->order->customer->fullname,
                'dob' => $this->order->customer->dob,
                'age' => $this->order->customer->getAge(),
            ];
        }

        return $customers;
    }


    public function getDosageInfo()
    {
        if (empty($this->item)) {
            return null;
        }

        if ($this->pharmacy_label_text) {
            return $this->pharmacy_label_text;
        }

        if (!empty($this->item_size->custom->dosage)) {
            return $this->item_size->custom->dosage;
        }

        if (!empty($this->item->custom->dosage)) {
            return $this->item->custom->dosage;
        }

        return null;
    }

   public static function newFactory()
   {
       return new OrderItemsFactory();
   }
}
