<?php

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\KupShopBundle\Query\JsonOperator;
use Query\Operator;

class PhotosList extends BaseList
{
    protected $template = 'list/photos.tpl';
    protected $pageDivide = 150;

    protected $orderParam = [
        'sort' => 'Datum',
        'direction' => 'DESC',
    ];

    protected $tableDef = [
        'id' => 'id',
        'fields' => [
            'Obrázek' => ['field' => 'id'],
            'Název' => ['field' => 'descr'],
            'Datum' => ['field' => 'date'],
        ],
    ];

    public function getSQL(Query\QueryBuilder $qb)
    {
        global $cfg;
        $data = parent::getSQL($qb);
        $links = [];
        foreach ($data['SQL'] as $key => $row) {
            $links[$key] = $row;
            $links[$key]['img'] = getImage($row['id'], $row['image_2'], $row['source'], 4, $row['descr'], strtotime($row['date_update']));
        }
        $data['SQL'] = $links;

        return $data;
    }

    public function getPageDivide()
    {
        if (getVal('searchWnd')) {
            return parent::getPageDivide() - 1;
        }

        return parent::getPageDivide();
    }

    public function handleUploadImage()
    {
        $success = 'false';
        $photoId = null;

        $image = getVal('uploader', $_FILES);
        $filename = getVal('qqfilename');

        if (!empty($image)) {
            $photoId = $this->uploadImage($image, $filename);
            if ($photoId) {
                $success = 'true';
            }
        }

        header('Content-Type: application/json');
        echo json_encode([
            'success' => $success,
            'id' => $photoId,
        ]);
        exit;
    }

    protected function uploadImage($image, $filename)
    {
        $img = new Photos('none');
        $img->newImage($this->getID());
        // uploadovat obrazek
        $img->uploadPhotoOrVideo($image, $filename);

        return $img->getID();
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('p.*')
            ->from('photos', 'p')
            ->groupBy('p.id');

        if (findModule(Modules::VIDEOS)) {
            $qb->addSelect('v.id_cdn id_video')
                ->leftJoin('p', 'videos', 'v', 'p.id = v.id_photo');
        }

        extract($_GET, EXTR_SKIP | EXTR_REFS);

        if ($photosType = getVal('photos_type')) {
            $objectIdField = null;

            switch ($photosType) {
                case 'products':
                    $objectIdField = 'ppr.id_product';
                    $qb->join('p', 'photos_products_relation', 'ppr', 'p.id = ppr.id_photo');
                    break;
                case 'pages':
                    $objectIdField = null;

                    $qb->leftJoin('p', 'photos_menu_relation', 'ppr', 'p.id = ppr.id_photo')
                        ->leftJoin('p', 'photos_blocks_new_relation', 'pbnr', 'p.id = pbnr.id_photo');

                    if ($objectId = getVal('id_object')) {
                        $spec = Operator::orX(
                            Operator::equals(['ppr.id_menu' => $objectId]),
                            'pbnr.id_block IN (b.id)'
                        );
                        $qb->leftJoin('p', 'menu_links', 'ml', 'ml.id = :page_object_id')
                            ->leftJoin('ml', 'blocks', 'b', 'b.id_root = ml.id_block')
                            ->andWhere($spec)
                            ->setParameter('page_object_id', $objectId);
                    }

                    break;
                case 'articles':
                    $objectIdField = 'ppr.id_art';
                    $qb->join('p', 'photos_articles_relation', 'ppr', 'p.id = ppr.id_photo');
                    break;
                case 'producers':
                    $objectIdField = 'ppr.id_producer';
                    $qb->join('p', 'photos_producers_relation', 'ppr', 'p.id = ppr.id_photo');
                    break;
                case 'no':
                    $qb->leftJoin('p', 'photos_products_relation', 'ppr', 'p.id = ppr.id_photo')
                        ->leftJoin('p', 'photos_producers_relation', 'pprr', 'p.id = pprr.id_photo')
                        ->leftJoin('p', 'photos_articles_relation', 'par', 'p.id = par.id_photo')
                        ->leftJoin('p', 'photos_menu_relation', 'pmr', 'p.id = pmr.id_photo')
                        ->andWhere('ppr.id_photo IS NULL AND pprr.id_photo IS NULL AND par.id_photo IS NULL AND pmr.id_photo IS NULL');
                    break;
                case 'videos':
                    $objectIdField = 'p.id';
                    $qb->andWhere('v.id_photo is not null');
                    break;
                case 'photos':
                    $objectIdField = 'p.id';
                    if (findModule(Modules::VIDEOS)) {
                        $qb->andWhere('v.id_photo is null');
                    }
                    break;
            }

            if (($objectId = getVal('id_object')) && $objectIdField) {
                $qb->andWhere(\Query\Operator::equals([$objectIdField => $objectId]));
            }
        }

        if ($filename = getVal('filename')) {
            $qb->andWhere('p.filename LIKE :filename')
                ->setParameter('filename', '%'.$filename.'%');
        }

        if ($descr = getVal('descr')) {
            $qb->andWhere('p.descr LIKE :descr')
                ->setParameter('descr', '%'.$descr.'%');
        }

        // ###########
        if (!empty($_GET['IDp'])) {
            $qb->from('photos_products_relation', 'pp')->andWhere('p.id=pp.id_photo')->andWhere('pp.id_product=:IDp')
                ->setParameter('IDp', $_GET['IDp']);
        }
        // ###########
        if (!empty($_GET['IDa'])) {
            $qb->from('photos_articles_relation', 'pa')->andWhere('p.id=pa.id_photo AND pa.id_art=":IDa" ')
            ->setParameter('IDa', $_GET['IDa']);
        }
        // ###########
        if (!empty($_GET['name'])) {
            $qb->andWhere('p.descr LIKE "%'.$_GET['name'].'%" ');
        }
        // ###########
        if (!empty($_GET['ID'])) {
            $qb->andWhere(Operator::equals(['p.id' => intval($_GET['ID'])]));
        }
        // ###########
        if (!empty($_GET['year'])) {
            if ($_GET['year'] == 'null') {
                $qb->andWhere('p.date=0');
            } else {
                $qb->andWhere('YEAR(p.date)=:year')->setParameter('year', $_GET['year']);
            }
        }
        // ###########
        if (!empty($_GET['month'])) {
            $qb->andWhere('MONTH(p.date)=:month')->setParameter('month', $_GET['month']);
        }
        // ###########
        if (!empty($_GET['check'])) {
            $qb->andWhere(JsonOperator::exists('p.data', 'invalid'));
        }

        return $qb;
    }
}
