<?php

declare(strict_types=1);

namespace External\PompoBundle\Util\Export;

use Query\Product;
use Query\QueryBuilder;

class OSSExport
{
    public function export()
    {
        $qb = $this->getQueryBuilder();

        header('Content-type: application/xls');
        header('Content-Disposition: attachment; filename="products-oss-export.csv"');

        $header = [
            'Kód produktu',
            'Název produktu',
            'CN kód',
            'DPH u produktu',
            'DPH [CZ]',
            'DPH [SK]',
        ];

        $fp = fopen('php://output', 'w');
        fputcsv($fp, $header);
        foreach ($qb->execute() as $item) {
            fputcsv($fp, $item, ';');
        }
        fclose($fp);
    }

    public function getQueryBuilder(): QueryBuilder
    {
        return sqlQueryBuilder()
            ->select('p.code, p.title, p.id_cn, v.vat')
            ->fromProducts()
            ->leftJoin('p', 'vats', 'v', 'v.id = p.vat')
            ->andWhere(Product::withVats(['CZ', 'SK']))
            ->groupBy('p.id');
    }
}
