<?php

use KupShop\AdminBundle\Util\Export\ExportUsers;
use KupShop\AdminBundle\Util\UsersFilterSpecs;

require_once $cfg['Path']['shared_version'].'admin/board/board.export_users.php';

$main_class = 'ShopExportUsersBoard';

class ShopExportUsersBoard extends ExportUsersBoard
{
    public function handle()
    {
        // Sorry ale už se mi nechce ty dva exporty předělávat na servisy ....
        $usersFilterSpecs = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(UsersFilterSpecs::class);

        if (getVal('Submit')) {
            $export = new ExportUsers($usersFilterSpecs);

            $export->exportCSV();
        }

        if (getVal('SubmitExpired')) {
            $export = new ExportExpiredUsers($usersFilterSpecs);

            $export->exportCSV();
        }
    }
}

class ExportExpiredUsers extends ExportUsers
{
    use DatabaseCommunication;

    public function exportCSV()
    {
        sqlGetConnection()->getWrappedConnection()->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

        $users = sqlQueryBuilder()->select("u.email, u.id, u.figure, u.get_news,
            COALESCE(IF(u.date_reg = '0000-00-00 00:00:00', u.date_updated, u.date_reg), u.date_subscribe) AS date_registered,
            u.date_subscribe, u.date_unsubscribe, GROUP_CONCAT(ug.name SEPARATOR ';') as groups")
            ->from('users', 'u')
            ->leftJoin('u', 'orders', 'o', 'o.invoice_email = u.email')
            ->leftJoin('u', 'users_groups_relations', 'ugr', 'u.id = ugr.id_user')
            ->leftJoin('ugr', 'users_groups', 'ug', 'ugr.id_group = ug.id')
            ->where('o.invoice_email IS NULL')
            ->groupBy('u.id')
            ->having('date_registered IS NULL OR date_registered <= DATE_SUB(NOW(), INTERVAL 5 YEAR)')
            ->orderBy('date_registered', 'DESC');

        $users = $users->execute();

        $filename = 'users_expired_'.date('Y-m-d_H-i').'.csv';

        header('Content-type: application/csv');
        header("Content-Disposition: attachment; filename=\"{$filename}\"");

        $smarty = createSmarty(true, true);
        $smarty->assign([
            'users' => $users,
        ]);

        $smarty->display('export/users_expired_csv.tpl');

        writeDownActivity("Export uživatelů (expired): {$filename}");
        exit;
    }
}
