<?php

namespace App\Console\Commands;

use App\Models\Category;
use App\Models\News;
use App\Models\AgencyBotCategory;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use App\Models\Setting;
use Illuminate\Support\Facades\File;

class İhaAJans extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:ihaajans';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'İha AJans Haber Verilerini Burada Çekiyoruz';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }



    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $ihabotstatus=Setting::where('id',23)->first();
      

        if($ihabotstatus->value==1) {

        $ihabotcount=Setting::where('id',25)->first();
        $ihabotimage=Setting::where('id',26)->first();
        $ihabotuserCode=Setting::where('id',27)->first();
        $ihabotuserName=Setting::where('id',28)->first();
        $ihabotuserPassword=Setting::where('id',29)->first();
        $ihabotuserCity=Setting::where('id',77)->first();



        $iha=simplexml_load_file(urlencode('https://abonerss.iha.com.tr/xml/standartrss?UserCode='.$ihabotuserCode->value.'&UstKategori=0&UserName='.$ihabotuserName->value.'&UserPassword='.$ihabotuserPassword->value.'&Kategori=0&Sehir='.$ihabotuserCity->value.'&wp=0&tagp=0&tip=1')); 


        $items=$iha->channel->item;

        $i=0;
        foreach ($items as $item){
        $imagestatus=0;
        $kategori=$item->Kategori;
        $haberkodu=$item->HaberKodu;
        $title=$item->title;
        $description=$item->description;
        $pubDate=$item->pubDate;
        print_r($item->images);
        if(isset($item->images)){
            $attr=$item->images->image[0]->attributes();
            $images=$item->images->image[0];
            $imagestatus=1;
        }

        $findhaber=News::where('botNews_id',$haberkodu)->count();


        if($findhaber == 0){

            $findCategory=AgencyBotCategory::where('bot_category_name',$kategori)->where('bot_id',1)->count();

                if($findCategory > 0){

                    $getCategory=AgencyBotCategory::where('bot_category_name',$kategori)->where('bot_id',1)->first();

                    if($getCategory->bot_category_status==1){

                       $getCategory->category->name.'---';
                               $date=explode(' ',$pubDate);
                               $datedate=explode('.',$date[0]);
                                          if($imagestatus==1){
                                
                                                    $year = $datedate[2];
                                                    $month = $datedate[1];
                                                    $day = $datedate[0];

                                                    // Dosya yolu
                                                    $destinationPath = public_path("/uploads/images/news/$year/$month/$day");

                                                    // Klasör mevcut değilse oluştur
                                                    if (!File::exists($destinationPath)) {
                                                        File::makeDirectory($destinationPath, 0777, true, true);
                                                    }

                                                    // Resim kodunu al ve tam dosya yolunu belirle
                                                    $imagePath = $destinationPath . '/' . $attr['ResimKodu'] . '.jpg';

                                                // Kopyalama işlemi
                                                if (copy($images, $imagePath)) {
                                                    // Kopyalama başarılıysa, hedef dosyanın var olup olmadığını kontrol et
                                                    if (!file_exists($imagePath)) {
                                                        // Eğer hedef dosya mevcut değilse, imagestatus 0 yap
                                                        $imagestatus = 0;
                                                    } else {
                                                        // Dosyanın boyutunu kontrol et (1000 KB = 1000000 bytes)
                                                        if (filesize($imagePath) < 100000) {
                                                            // Eğer dosya boyutu 1000 KB'den küçükse, imagestatus 0 yap
                                                            $imagestatus = 0;
                                                        }
                                                    }
                                                } else {
                                                    // Eğer kopyalama işlemi başarısız olursa imagestatus 0 yap
                                                    $imagestatus = 0;
                                                }
                                            }


                                    if($imagestatus==1){
                                        $newSound= new News();
                                        $newSound->category_id=$getCategory->category->id ?? 0;
                                        $newSound->source_id=1;
                                        $newSound->author_id=0;
                                        $newSound->photo_gallary_id=0;
                                        $newSound->video_gallary_id=0;
                                        $newSound->date=$date[0];
                                        $newSound->time=$date[1];
                                        $newSound->name=$item->title;
                                        $newSound->slug=slug(Str::ascii(html_entity_decode($item->title),"tr"));
                                        $newSound->description=$item->description;
                                        $newSound->status=1;
                                        $newSound->is_headline=0;
                                        $newSound->is_mainheadline=0;
                                        $newSound->corner_post=0;
                                        $newSound->is_lastminute=0;
                                        $newSound->is_breaking=0;
                                        $newSound->is_photogallary=0;
                                        $newSound->is_videogallary=0;
                                        $newSound->botNews_id=$haberkodu;
                                        if($getCategory->bot_artificial_intelligence_status==0){
                                            $newSound->kaynak="İha Haber Ajansı";
                                        }
                                        if($imagestatus==1){
                                          $newSound->news_image = $attr['ResimKodu'] . '.jpg';
                                        }else{
                                           $newSound->news_image = 'notimage2.png';
                                        }
                                        $newSound->save();
                                        $i=$i+1;
                                        echo $item->title .' Eklendi </br>';
                                    }else{
                                        echo $item->title ."Resimsiz Haber Eklenmiyor </br>";
                                    }
                            
                                if($i==$ihabotcount->value){
                                     exit();
                                }
                    }
                }
            }else{
                 echo $item->title .'Haber Daha Önce Eklendi </br>';
            }
        }
    }else{
        echo "Bot Aktif Değil";
    }

        return Command::SUCCESS;
    }
}
