<?php

namespace App\Console\Commands;

use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\ServiceProvider;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class GetServiceCron extends Command {
    protected $signature = 'get_service:cron';
    protected $description = 'Command description';
    public function __construct() {
        parent::__construct();
    }
    private function round_price($price) {
        $zeros = log($price) * log10(M_E) | 0;
        $zeros = min($zeros, 2); // Only round to tens, hundreds or thousands
        $tens = pow(10, $zeros);
        return ceil($price / $tens) * $tens;
    }
    public function handle() {
        $provider = ServiceProvider::where('name', 'WSTORE')->first();
        if ($provider == false) return $this->info('Penyedia tidak ditemukan.');
        if ($provider->name == 'SMMTRY') {
            $post_api = array(
                'action'    => 'services',
                'api_key' => $provider->provider_key,
            );
            $curl = post_curl($provider->provider_url_service, $post_api);
            $curl_response = json_decode($curl, true);
            if (isset($curl_response['status']) AND $curl_response['status'] == false) return $this->info('Proses gagal.');
            // print("<pre>".print_r($curl_response,true)."</pre>");
            foreach ($curl_response['data'] as $service) {
                if ($service['price'] <= 200) {
                    $profit = (5 * $service['price']) - $service['price'];
                } elseif ($service['price'] <= 300) {
                    $profit = (4 * $service['price'])  - $service['price'];
                } elseif ($service['price'] <= 500) {
                    $profit = (3 * $service['price']) - $service['price'];
                } elseif ($service['price'] <= 999) {
                    $profit = (2 * $service['price']) - $service['price'];
                } elseif ($service['price'] <= 2000) {
                    $profit = (2 * $service['price']) - $service['price'];
                } elseif ($service['price'] <= 9999) {
                    $profit = ceil(((50/100) * $service['price']));
                } elseif ($service['price'] <= 20000) {
                    $profit = ceil(((40/100) * $service['price']));
                } elseif ($service['price'] <= 30000) {
                    $profit = ceil(((30/100) * $service['price']));
                } elseif ($service['price'] > 30000) {
                    $profit = ceil(((10/100) * $service['price']));
                }
                $service_name = $service['name'];
                $check_category = ServiceCategory::where('name', $service['category'])->first();
                if ($check_category == false) {
                    $insert_category = ServiceCategory::create([
                        'name' => $service['category']
                    ]);
                    $category_id = $insert_category->id;
                } else {
                    $category_id = $check_category->id;
                }
                $check_service = Service::where([
                    ['provider_service_id', $service['id']],
                    ['provider_id', $provider->id]
                ])->first();
                if ($check_service == false) {
                    $insert_product = Service::create([
                        'category_id'         => $category_id,
                        'name'                => $service_name,
                        'price'               => $service['price'] + $profit,
                        'profit'              => $profit,
                        'min'                 => $service['min'],
                        'max'                 => $service['max'],
                        'description'         => $service['note'],
                        'provider_id'         => $provider->id,
                        'provider_service_id' => $service['id'],
                    ]);
                    if ($insert_product == true) {
                        $this->info('Layanan Berhasil ditambahkan kedalam database <br />');
                    }
                } else {
                    $update_product = $check_service->update([
                        'name'                => $service_name,
                        'price'               => $service['price'] + $profit,
                        'profit'              => $profit,
                        'min'                 => $service['min'],
                        'max'                 => $service['max'],
                    ]);
                    if ($update_product == true) {
                        $this->info('Layanan Berhasil diperbarui dari database <br />');
                    }
                }
            }
        } elseif ($provider->name == 'TokoInfluencer') {
            $post_api = array(
                'action'    => 'services',
                'key' => $provider->provider_key,
            );
            $curl = post_curl($provider->provider_url_service, $post_api);
            $curl_response = json_decode($curl, true);
            if (isset($curl_response['status']) AND $curl_response['status'] == false) return $this->info('Proses gagal.');
            // print("<pre>".print_r($curl_response,true)."</pre>");
            foreach ($curl_response as $service) {
                $service['price'] = $service['rate'];
                $profit = 0;
                $service_name = $service['name'];
                $check_category = ServiceCategory::where('name', $service['category'])->first();
                if ($check_category == false) {
                    $insert_category = ServiceCategory::create([
                        'name' => $service['category']
                    ]);
                    $category_id = $insert_category->id;
                } else {
                    $category_id = $check_category->id;
                }
                $check_service = Service::where([
                    ['provider_service_id', $service['service']],
                    ['provider_id', $provider->id]
                ])->first();
                if ($check_service == false) {
                    $insert_product = Service::create([
                        'category_id'         => $category_id,
                        'name'                => $service_name,
                        'price'               => $service['price'] + $profit,
                        'profit'              => $profit,
                        'min'                 => $service['min'],
                        'max'                 => $service['max'],
                        'description'         => '',
                        'provider_id'         => $provider->id,
                        'provider_service_id' => $service['service'],
                        'type'                => $service['type'] == 'Custom Comments' ? $service['type'] : '',
                        'is_refill_support'   => $service['refill'] == true ? '1' : '0',
                    ]);
                    if ($insert_product == true) {
                        $this->info('Layanan Berhasil ditambahkan kedalam database <br />');
                    }
                } else {
                    $update_product = $check_service->update([
                        'name'                => $service_name,
                        'price'               => $service['price'] + $profit,
                        'profit'              => $profit,
                        'min'                 => $service['min'],
                        'max'                 => $service['max'],
                        'type'                => $service['type'] == 'Custom Comments' ? $service['type'] : '',
                        'is_refill_support'   => $service['refill'] == true ? '1' : '0',
                    ]);
                    if ($update_product == true) {
                        $this->info('Layanan Berhasil diperbarui dari database <br />');
                    }
                }
            }
        } elseif ($provider->name == 'WSTORE') {
            $post_api = array(
                'api_id'     => $provider->provider_id,
                'api_key'    => $provider->provider_key,
                'secret_key' => $provider->provider_secret,
            );
            $curl = post_curl('https://www.wstore.co.id/api/services', $post_api);
            $curl_response = json_decode($curl, true);
            if (isset($curl_response['response']) AND $curl_response['response'] == false) return $this->info('Proses gagal. '.$curl_response['data']['msg'].'');
            // print("<pre>".print_r($curl_response,true)."</pre>");
            foreach ($curl_response['data'] as $service) {
                $service['price'] = $service['price'];
                $profit = ceil(((10/100) * $service['price']));
                $profitPrice = $this->round_price($service['price']) + $this->round_price($profit) - $service['price'];
                $totalPrice = ($this->round_price($service['price']) + $this->round_price($profit));
                $service_name = strtr($service['service_name'], array(
                    '♻️' => '',
                    '??' => '',
                ));
                $check_category = ServiceCategory::where('name', $service['category_name'])->first();
                if ($check_category == false) {
                    $insert_category = ServiceCategory::create([
                        'name' => $service['category_name']
                    ]);
                    $category_id = $insert_category->id;
                } else {
                    $category_id = $check_category->id;
                }
                $check_service = Service::where([
                    ['provider_service_id', $service['id']],
                    ['provider_id', $provider->id]
                ])->first();
                if ($check_service == false) {
                    // $insert_product = Service::create([
                    //     'category_id'         => $category_id,
                    //     'name'                => $service_name,
                    //     'price'               => $totalPrice,
                    //     'profit'              => $profitPrice,
                    //     'min'                 => $service['min'],
                    //     'max'                 => $service['max'],
                    //     'description'         => $service['description'],
                    //     'provider_id'         => $provider->id,
                    //     'provider_service_id' => $service['id'],
                    //     'type'                => $service['type'],
                    //     'is_refill_support'   => $service['refill'] == true ? '1' : '0',
                    //     'settings' => json_encode([
                    //         'update_service'  => '1',
                    //         'name' 			  => '1',
                    //         'min_max' 		  => '1',
                    //         'price_profit' 	  => '1',
                    //         'profit' 		  => '1',
                    //         'description'     => '1',
                    //         'custom_comments' => '1',
                    //         'refill_support'  => '1',
                    //         'status'  		  => '1',
                    //     ])
                    // ]);
                    // if ($insert_product == true) {
                    //     $this->info('Layanan Berhasil ditambahkan kedalam database <br />');
                    // }
                } else {
                    $update_product = $check_service->update([
                        'price'               => $service['price'] + $profit,
                        'profit'              => $profit,
                        'min'                 => $service['min'],
                        'max'                 => $service['max'],
                        'description'         => $service['description'],
                        'type'                => $service['type'],
                        'is_refill_support'   => $service['refill'] == '1' ? $service['refill'] : '0',
                    ]);
                    if ($update_product == true) {
                        $this->info('Layanan Berhasil diperbarui dari database <br />');
                    }
                }
            }
        }
    }
}
