<?php

class ControllerpiyerSoftDevice extends Controller
{

    public function index()
    {
        
        //error_reporting(0);

        //$userAgent = $_SERVER['HTTP_USER_AGENT'];
        $fullName = '';
        $userIp = $_SERVER['REMOTE_ADDR'];
        $banners = $sliders = $properties = [];
        $videoBannerData = ['video_code' => '', 'html_code' => ''];

        # deercase deviceatlas'ı kullanmıyor. -Can 16.03.2022
        /*
        //if (isset($_COOKIE['DADEVICE']) && !empty($_COOKIE['DADEVICE']) && $_COOKIE['DADEVICE'] != 'other') {
        if (1==2) {

            $fullName = str_replace('_', ' ', $_COOKIE['DADEVICE']);

            $properties = ['cookie' => 'yes'];

        }
        else {

            require_once('deviceatlas/Client.php');

            try {

                $result = DeviceAtlasCloudClient::getDeviceData(); //dd($result);

                if (isset($result['properties'])) {

                    $properties = $result['properties'];

                    if ($result['properties']['isMobilePhone']) { //|| $result['properties']['mobileDevice']

                        $manufacturer = str_replace(' ','_', $result['properties']['manufacturer']);

                        $modelName = '';
                        if (!empty($result['properties']['marketingName'])) {
                            $modelName = $result['properties']['marketingName'];
                        }
                        else if (!empty($result['properties']['model'])) {
                            $modelName = $result['properties']['model'];
                        }

                        $fullName = $manufacturer . ' ' . $modelName;

                        setcookie('DADEVICE', str_replace(' ','_', $fullName),time()+60*60*24, '/');

                        $this->logDb($userIp, $manufacturer, $modelName, $result['properties']['marketingName']);//$userAgent,

                    }
                    else {
                        setcookie('DADEVICE', 'other', time()+60*60*24*365, '/');
                        echo json_encode(['properties' => $properties]);
                        //echo '{}';
                        return true;
                        //$this->log('other');
                    }

                }
                else {
                    echo json_encode(['result' => $result]);
                    //echo '{}';
                    return true;
                }


            } catch (Exception $e) {
                die ($e->getMessage());
            }

        }

        */

        //find category and banners
        if (!empty($fullName)) {

            $categoryId = $this->db->query("SELECT category_id FROM ps_category_description WHERE full_name='$fullName' LIMIT 1")->row['category_id'] ?? 0;

            if (isset($categoryId) && !empty($categoryId)) {

                $videoBannerResult = $this->db->query("SELECT video_code, html_code FROM ps_banner WHERE model=$categoryId ")->row;

                if (!empty($videoBannerResult['video_code']) && !empty($videoBannerResult['html_code'])) {
                    $videoBannerData = [
                        'video_code' => html_entity_decode($videoBannerResult['video_code']),
                        'html_code' => html_entity_decode($videoBannerResult['html_code'])
                    ];
                }

                $bannerResult = $this->db->query("SELECT bi.link, bi.image, bi.model_id FROM ps_banner b LEFT JOIN ps_banner_image bi ON bi.banner_id=b.banner_id WHERE b.model=$categoryId ")->rows;

                if ($bannerResult && count($bannerResult) > 0) {

                    foreach ($bannerResult as $resultItem) {
                        if ($resultItem['model_id'] < 1000) {
                            $banners[] = $resultItem;
                        }
                        elseif ($resultItem['model_id'] > 5000) {
                            $sliders[] = $resultItem;
                        }
                    }

                }

            }

            echo json_encode(['banners' => $banners, 'sliders' => $sliders, 'properties' => $properties, 'category_id' => $categoryId ?? 0, 'video_banner' => $videoBannerData]);

        }
        
    }


    public function logDb($ip, $manufacturer, $model, $marketingName)//$userAgent,
    {
        //user_agent='$userAgent',
        $this->db->query("INSERT INTO rs_device_log SET date=NOW(), ip='$ip', manufacturer='$manufacturer', model='$model', marketing_name='$marketingName' ");

    }

    public function logFile($manufacturer, $modelName='')
    {
        $deviceLogFile = @fopen('/home/deer2piyersoft/public_html/log/device_detect/device_log_'.date("ymd").'.txt', 'a');
        @fwrite($deviceLogFile, '['.date("d.m.Y h:i:s").']('.$_SERVER['REMOTE_ADDR'].')'.$manufacturer . '_' . $modelName."\n");
        @fclose($deviceLogFile);
    }


}