<?php

namespace KupShop\ElninoBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class RemoveProductPhotosWithoutAbraPictures extends Script
{
    protected static $name = 'Odstranit produktové fotky (photos) bez relevantního řádku v abra_pictures';

    protected static $defaultParameters = [
        'dryRun' => true,
    ];

    protected function run(array $arguments)
    {
        $this->log('Starting...');

        sqlQueryBuilder()->select();

        $rows = sqlQuery("
            SELECT ppr.id_product, p.id AS id_photo, p.source, p.image_2 FROM photos_products_relation ppr
            LEFT JOIN abra_pictures ap ON ap.id_picture = ppr.id_photo
            LEFT JOIN photos p ON p.id=ppr.id_photo
            WHERE ap.id_abra IS NULL AND p.source LIKE 'shared/%';
        ")->fetchAll();
        $count = 0;
        foreach ($rows as $row) {
            $count++; // invalid photos +1
            echo '<br/><br/>'.PHP_EOL.PHP_EOL;
            print_r($row);
            if ($arguments['dryRun']) {
                continue;
            }
            sqlQueryBuilder()->delete('photos')->where(Operator::equals([
                'id' => $row['id_photo'],
            ]))->execute();
            echo ' ... removed';
        }

        echo '<br/><br/>'.PHP_EOL.PHP_EOL;
        if ($arguments['dryRun']) {
            $this->log("Celkem nalezeno {$count} záznamů.");
        } else {
            $this->log("Hotovo. Odstraněno {$count} záznamů.");
        }
    }
}

return RemoveProductPhotosWithoutAbraPictures::class;
