<?php
if (!defined('ABSPATH')) exit;

require_once dirname(__DIR__) . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class SOQE_Export
{
    public static function get_orders($from, $to, $status)
    {
        $args = [
            'limit' => -1,
            'orderby' => 'date',
            'order' => 'DESC',
        ];
        if ($from && $to) {
            $args['date_created'] = $from . '...' . $to;
        }
        if ($status && strpos($status, 'wc-') === 0) {
            $args['status'] = [$status];
        }
        return wc_get_orders($args);
    }

    public static function generate_csv($from = '', $to = '', $status = '')
    {
        while (ob_get_level()) { ob_end_clean(); }

        $orders = self::get_orders($from, $to, $status);

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=orders-' . gmdate('Y-m-d-His') . '.csv');
        $output = fopen('php://output', 'w');

        // Delimitator compatibil Excel RO
        $delimiter = ';';

        fputcsv($output, [
            'ID',
            'Date',
            'Customer',
            'Email',
            'Phone',
            'Total',
            'Status',
            'Products'
        ], $delimiter);

        foreach ($orders as $order) {
            $items = [];
            foreach ($order->get_items() as $item) {
                $items[] = $item->get_name() . ' (x' . $item->get_quantity() . ')';
            }
            fputcsv($output, [
                $order->get_id(),
                $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i') : '',
                $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
                $order->get_billing_email(),
                $order->get_billing_phone(),
                $order->get_total(),
                wc_get_order_status_name($order->get_status()),
                implode(' / ', $items),
            ], $delimiter);
        }

        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        fclose($output);
        exit;
    }

    public static function generate_excel($from = '', $to = '', $status = '')
    {
        while (ob_get_level()) { ob_end_clean(); }

        $orders = self::get_orders($from, $to, $status);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->fromArray(
            ['ID', 'Date', 'Customer', 'Email', 'Phone', 'Total', 'Status', 'Products'],
            NULL,
            'A1'
        );
        $row = 2;
        foreach ($orders as $order) {
            $items = [];
            foreach ($order->get_items() as $item) {
                $items[] = $item->get_name() . ' (x' . $item->get_quantity() . ')';
            }
            $sheet->fromArray([
                $order->get_id(),
                $order->get_date_created() ? $order->get_date_created()->date('Y-m-d H:i') : '',
                $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
                $order->get_billing_email(),
                $order->get_billing_phone(),
                $order->get_total(),
                wc_get_order_status_name($order->get_status()),
                implode('; ', $items),
            ], NULL, 'A' . $row);
            $row++;
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="orders-' . gmdate('Y-m-d-His') . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}
