<?php

namespace App\Models;

use App\Traits\HasCacheModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory;
    use HasCacheModel;

    const STATUS_COMPLETED = 'COMPLETED';
    const STATUS_PENDING = 'PENDING';
    const STATUS_CANCELED = 'CANCELED';

    public function __construct()
    {
        $this->table = 'orders';
        $this->guarded = [];
    }
    public static function getOrdersWithDiscountAndPackage()
    {
        return self::select(
            'orders.*',
            'users.name as user_name',
            'users.email as user_email',
            'users.phone as user_phone',
            'users.company as user_company',
            'users.country_code',
            'users.avatar',
            'h_country.name as user_country',
            'discount.value as discount_value',
            'discount_type.name as discount_type',
            'package.title as package_name',
            \DB::raw(
                'CASE WHEN discount_type.name = "percent"
                THEN
                    ROUND((orders.package_price * discount.value) / 100, 2)
                ELSE
                    CASE
                        WHEN ROUND(orders.package_price - discount.value, 2) < 0 THEN ROUND(orders.package_price, 2)
                        ELSE ROUND(discount.value, 2)
                    END
                END
                as discounted_package_price'
            )
        )
            ->leftJoin('users', 'users.id', '=', 'orders.user_id')
            ->leftJoin('h_country', 'h_country.code', '=', 'users.country_code')
            ->leftJoin('discount', 'discount.code', '=', 'orders.discount')
            ->leftJoin('package', 'package.id', '=', 'orders.package_id')
            ->leftJoin('discount_type', 'discount_type.id', '=', 'discount.discount_type_id');
    }
}
