<?php
namespace App\Libs;
use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\AdCat;
use App\Models\Ads;
use App\Models\Lookup;
use DateTime;
class AppAds 
{
    public static function getAds($typ, $pg = 1) {
        $rs = Ads::where('status',0)->orderBy('featured','desc')->orderBy('pdate','desc')->paginate(20);
        $lst = array();
        foreach($rs as $row) {
            $a = AppAds::formatAd($row);
            array_push($lst, $a);
        }
        // $rs = Ads::where('status',0)->where('featured',0)->orderBy('pdate','desc')->get()->toArray();
        // foreach($rs as $row) {
        //     $a = AppAds::formatAd($row);
        //     array_push($lst, $a);
        // }
        return $rs;
    }
    public static function formatAd($row) {
        $a = $row;
        $rs = AdCat::join('ads','ads.id','ads_cat.ad_id')
                ->join('lookup', 'lookup.id', 'ads_cat.id')
                ->where('ads.status',0)
                ->where('ads.id', $row['id'])
                ->select('lookup.val', 'lookup.slug')
                ->orderBy('lookup.val')
                ->get();
        $cats = array();
        foreach($rs as $s) {
            $x = array();
            $x['name'] = $s['val'];
            $x['slug'] = $s['slug'];
            array_push($cats, $x);
        }
        $a['cat'] = $cats;
        $a['posted'] = AppAds::timeElapsed($row['pdate']);
        return $a;
    }
    public static function timeElapsed($dateString) {
        $inputDate = new DateTime($dateString);
        $today = new DateTime();
        $interval = $inputDate->diff($today);
        $out = date('d/m/Y', strtotime($dateString));
        if ($interval->y === 0 && $interval->m === 0) {
            if($interval->d == 0) {
                $out = "Today";
            } elseif($interval->d == 1) {
                $out = "1 day ago";
            } else {
                $out = $interval->d." days ago";
            }
            
        }
        return $out;
         
    }
    public static function getCategories() {
        $rs = AdCat::join('ads','ads.id','ads_cat.ad_id')
                ->join('lookup', 'lookup.id', 'ads_cat.id')
                ->where('ads.status',0)
                ->select('lookup.val', 'lookup.slug')
                ->orderBy('lookup.val')
                ->get()
                ->toArray();
        return $rs;
    }
}
