<?php

$main_class = 'ExportSalableProductsBoard';

class ExportSalableProductsBoard extends Frame
{
    protected $template = 'board/export_salable_products.tpl';

    public function handle()
    {
        if (getVal('Submit')) {
            if ($_FILES['productIDsToCheck']['error'] != 0) {
                $this->returnError('Invalid file uploaded');
            }

            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=export_salable_products.csv');
            $output = fopen('php://output', 'w');

            $handle = fopen($_FILES['productIDsToCheck']['tmp_name'], 'r');
            // $headers = fgetcsv($handle, 1000, ",");
            $productIDsBatch = [];
            while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                if (!empty($data[0]) && !empty(trim($data[0]))) {
                    $productIDsBatch[$data[0]] = trim($data[0]);
                }
                if (count($productIDsBatch) >= 500) {
                    // check current batch
                    $resultBatch = $this->checkProductsBatch(array_values($productIDsBatch));
                    $productIDsBatch = []; // reset batch buffer

                    foreach ($resultBatch as $resultRow) {
                        fputcsv($output, $resultRow);
                    }
                }
            }
            // check the rest
            if (count($productIDsBatch)) {
                $resultBatch = $this->checkProductsBatch(array_values($productIDsBatch));
                foreach ($resultBatch as $resultRow) {
                    fputcsv($output, $resultRow);
                }
            }

            fclose($handle);
            fclose($output);

            exit;
        }
    }

    protected function checkProductsBatch(array $productIDs): array
    {
        return sqlQueryBuilder()->select('p.id AS id, MAX(producer.name) AS producer')->from('products', 'p')
            ->leftJoin('p', 'producers', 'producer', 'producer.id=p.producer')
            ->leftJoin('p', 'photos_products_relation', 'ppr', "ppr.id_product=p.id AND ppr.show_in_lead='Y'")
            ->andWhere(\Query\Operator::inStringArray($productIDs, 'p.id'))
            ->andWhere("p.figure != 'Y' OR p.in_store <= 0 OR p.price <= 0.00 OR ppr.id_photo IS NULL")
            ->groupBy('p.id')
            ->execute()->fetchAllAssociative();
    }
}
