<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Yajny\Models\Ad;
use Yajny\Models\Coupon;
use Yajny\Models\FeaturedStores;
use Yajny\Models\StoreCashback;
use Yajny\Models\StoreDeal;
use Yajny\Models\StripBanner;
use Yajny\Models\TopPicks;
use Yajny\Scopes\StatusScope;

class stores extends Central
{
    protected $table = 'stores';
    protected $primaryKey = 'id';
    protected $guarded = [];

    public $module = 'stores';
    public $timestamps = true;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     *
     *
     */
    protected static function boot()
    {
        parent::boot();
        static::updated(function ($store) {

            Log::info('saving .'.$store->status);
            if ( in_array($store->status, ['draft','trash'])) {
                // If status is being updated to 'draft' or 'trash', enable related tables
                $store->enableRelatedTables($store->id, $store->status);
            }
        });
    }

    /**
     * @param $store_id
     * @param $status
     */
    public function enableRelatedTables($store_id, $status)
    {

        // Enable related tables
        StoreDeal::where('store_id',$store_id)->withoutGlobalScopes()->update(['enabled' => false]);
        FeaturedStores::where('store_id',$store_id)->withoutGlobalScopes()->update(['status' => 'inactive']);
        TopPicks::where('store_id',$store_id)->withoutGlobalScopes()->update(['is_shown' => false]);
        Ad::where('store_id',$store_id)->withoutGlobalScopes()->update(['status' =>  'inactive']);
        Coupon::where('store_id',$store_id)->withoutGlobalScopes()->update(['status' => $status]);
        StoreCashback::where('store_id',$store_id)->withoutGlobalScopes()->update(['enabled' => false]);
        StripBanner::where('store_id',$store_id)->withoutGlobalScopes()->update(['is_active' => false]);
    }

    /**
     * @return string
     */
    public static function querySelect()
    {
        return "  SELECT stores.* FROM stores  ";
    }

    public static function queryWhere()
    {
        return "  WHERE stores.id IS NOT NULL ";
    }

    public static function queryGroup()
    {
        return "  ";
    }

    public function getExportHeaders() : array
    {
        return [
            'Store ID' => 'stores.id',
            'Store' => DB::raw("`stores`.`name`->>'$.en'"),
            'Slug' => 'stores.slug',
            'Cashback Status' => DB::raw("IF(`stores`.`cb_status`, 'Enabled', 'Disabled')"),
            'Status' => 'stores.status',
            'Updated At' => 'stores.updated_at',
            'Region Code' => 'stores.region_code'
        ];
    }


}
