<?php

if (!defined('_PS_VERSION_')) {
    exit;
}

class AdminEksportHistoriiController extends ModuleAdminController
{
    public function __construct()
    {
        $this->bootstrap = true;
        parent::__construct();
    }

    public function initContent()
    {
        if (Tools::isSubmit('submitExportHistory')) {
            $this->processExport();
            return;
        }

        parent::initContent();

        $this->content = $this->renderExportForm();

        $this->context->smarty->assign([
            'content' => $this->content,
        ]);
    }

    protected function renderExportForm()
    {
        $action = self::$currentIndex . '&token=' . $this->token;
        $action = Tools::safeOutput($action);

        $html = '
        <div class="panel">
            <h3><i class="icon-download"></i> ' . $this->l('Eksport historii zamówień') . '</h3>
            <form method="post" action="' . $action . '" class="form-horizontal">

                <div class="form-group">
                    <label class="control-label col-lg-2">
                        ' . $this->l('Data od') . '
                    </label>
                    <div class="col-lg-3">
                        <input type="date" name="date_from" class="form-control" required="required" />
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-lg-2">
                        ' . $this->l('Data do') . '
                    </label>
                    <div class="col-lg-3">
                        <input type="date" name="date_to" class="form-control" required="required" />
                    </div>
                </div>

                <div class="panel-footer">
                    <button type="submit" name="submitExportHistory" class="btn btn-primary">
                        <i class="icon-download"></i> ' . $this->l('Eksport do Excel (CSV)') . '
                    </button>
                </div>
            </form>
        </div>
        ';

        return $html;
    }

    /**
     * CSV
     */
    public function processExport()
    {
        $date_from = Tools::getValue('date_from');
        $date_to   = Tools::getValue('date_to');

        if (empty($date_from) || empty($date_to)) {
            die($this->l('Obie daty są wymagane.'));
        }

        // początek / koniec dnia
        $date_from .= ' 00:00:00';
        $date_to   .= ' 23:59:59';

        // Zapytanie SQL: zamówienia + klient + produkty
        $sql = new DbQuery();
        $sql->select('
            o.id_order AS order_id,
            c.id_customer AS client_id,
            c.email,
            c.firstname AS first_name,
            c.lastname AS last_name,
            od.product_id,
            od.product_name
        ');
        $sql->from('orders', 'o');
        $sql->innerJoin('customer', 'c', 'c.id_customer = o.id_customer');
        $sql->innerJoin('order_detail', 'od', 'od.id_order = o.id_order');
        $sql->where('o.date_add BETWEEN "' . pSQL($date_from) . '" AND "' . pSQL($date_to) . '"');
        $sql->orderBy('o.id_order ASC');

        $rows = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);

        $filename = 'orders_export_' . date('Y-m-d_His') . '.csv';

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');

        $output = fopen('php://output', 'w');

        fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF));

        fputcsv(
            $output,
            ['order_id', 'client_id', 'email', 'first_name', 'last_name', 'product_id', 'product_name'],
            ';'
        );

        if (!empty($rows)) {
            foreach ($rows as $row) {
                fputcsv(
                    $output,
                    [
                        $row['order_id'],
                        $row['client_id'],
                        $row['email'],
                        $row['first_name'],
                        $row['last_name'],
                        $row['product_id'],
                        $row['product_name'],
                    ],
                    ';'
                );
            }
        }

        fclose($output);
        exit;
    }
}
