<?php

namespace App\Jobs\Tasks;

use Illuminate\Support\Facades\DB;

class UpdateStoresCashback extends BaseTask
{
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $newCashbackPercent = $this->jobData['newCashbackPercent'];
        $storesCondition = '';
        if (isset($this->jobData['storesType'], $this->jobData['stores']) && $this->jobData['storesType'] != 'all' && $this->jobData['stores']) {
            switch ($this->jobData['storesType']) {
                case 'except':
                    $storesCondition = 'WHERE store_id NOT IN (' . implode(',', $this->jobData['stores']) . ')';
                    break;
                case 'only':
                    $storesCondition = 'WHERE store_id IN (' . implode(',', $this->jobData['stores']) . ')';
                    break;
            }
        }
        if ($newCashbackPercent) {
            DB::statement("UPDATE store_cashback SET rate_amount = rate_amount_network * {$newCashbackPercent} / 100 {$storesCondition}");
            DB::statement("UPDATE stores s LEFT JOIN (SELECT store_id, MAX(rate_amount) AS maxRate, FLOOR(MAX(rate_amount / rate_amount_network * 100)) AS cashbackPercentage FROM store_cashback WHERE enabled = 1 GROUP BY store_id) sc ON s.id = sc.store_id SET s.current_cb = COALESCE(sc.maxRate, current_cb * {$newCashbackPercent} / cashback_percent), s.cashback_percent = COALESCE(sc.cashbackPercentage, {$newCashbackPercent})");
        }
    }
}
