<?php

namespace KupShop\ElninoBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Config;

class RemoveDuplicitPictures extends Script
{
    protected static $name = 'Odstranit duplicitní obrázky';

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

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

        $qb = sqlQueryBuilder()->select('ap.id_abra, ap2.id_abra AS preserved_id_abra, ap.id_abra_product, ap.type, ap.id_picture, p.source, p.image_2')
            ->from('abra_pictures', 'ap')
            ->innerJoin('ap', 'abra_pictures', 'ap2', 'ap2.id_abra_product=ap.id_abra_product AND ap2.type=ap.type AND ap2.id_abra > ap.id_abra')
            ->leftJoin('ap', 'photos', 'p', 'p.id=ap.id_picture')
            ->where('ap.id_picture IS NOT NULL AND ap2.id_picture IS NOT NULL');

        echo 'abra_id to be removed => preserved abra_id, id_abra_product, abra type, file to be removed<br/>'.PHP_EOL;

        $cfg = Config::get();
        $counter = 0;
        $filesCounter = 0;
        foreach ($qb->execute() as $row) {
            $counter++;
            $originalPicturePath = $cfg['Path']['photos'].$row['source'].$row['image_2'];
            if ($fileExists = file_exists($originalPicturePath)) {
                $filesCounter++;
                echo "{$row['id_abra']} => {$row['preserved_id_abra']}, {$row['id_abra_product']}, {$row['type']}, '{$originalPicturePath}'<br/>".PHP_EOL;
            } else {
                echo "{$row['id_abra']} => {$row['preserved_id_abra']}, {$row['id_abra_product']}, {$row['type']}, --skipped--<br/>".PHP_EOL;
            }
            if ($arguments['dryRun']) {
                continue;
            }
            if ($fileExists) {
                unlink($originalPicturePath);
            }
            // deletion of row in photos also removes photos_products_relation and abra_pictures (both have ON DELETE CASCADE)
            sqlQueryBuilder()->delete('photos')
                ->where('id=:photo_id')->setParameter('photo_id', $row['id_picture'])
                ->execute();
        }

        if ($arguments['dryRun']) {
            $this->log("Celkem nalezeno {$counter} duplicitních záznamů a {$filesCounter} souborů ke smazání.");
        } else {
            $this->log("Hotovo. Odstraněno {$counter} duplicitních záznamů a {$filesCounter} souborů.");
        }
    }
}

return RemoveDuplicitPictures::class;
