<?php

namespace auctionforge\inc\controllers;

use auctionforge\inc\helpers\View;
use auctionforge\inc\InstanceDB;
use auctionforge\inc\model\SubmissionFormData;

class Submissions
{
    public function init() {
        if (defined('AUCTIONFORGE_SUBMISSIONS_FEATURE') && AUCTIONFORGE_SUBMISSIONS_FEATURE) {
            add_action('admin_menu', array($this, 'auction_register_admin_page_submissions'));
        }
    }

    public function auction_register_admin_page_submissions() {
        $hook = add_submenu_page(
            'edit.php?post_type=lot',
            __('Submissions Data', 'auctionforge'),
            __('Submissions', 'auctionforge'),
            'administrator',
            'auction_submissions',
            array($this, 'auction_submissions_page')
        );

        add_action("load-$hook", array($this, 'submissions_table_load'));
    }

    function submissions_table_load(){
        require_once __DIR__ . '/SubmissionsTable.php';

        if (!empty($_POST)) {
            $this->exportProcess();
        }

        $GLOBALS['SubmissionsTable'] = new SubmissionsTable();
    }

    public function auction_submissions_page()
    {
        echo View::render('admin.view.submissions', []);
    }

    private function exportProcess()
    {
        $path = plugin_dir_path(__FILE__) . '../../exports/';
        $fileName = "export_data-" . date("Y-m-d-h_s") . ".csv";

        $model = new SubmissionFormData();
        $rows = $model->getRows(0, -1);

        $ids = wp_list_pluck($rows, 'id');
        $model->updateExportedRecords($ids);

        if (!file_exists($path . $fileName)) {
            file_put_contents($path . $fileName, "", FILE_APPEND | LOCK_EX);
        }

        $fp = fopen($path . $fileName, 'w');

        if (!empty($rows)) {
            foreach ($rows as $row) {
                $data = json_decode($row->data);
                $files = (array)$data->files;
                unset($data->files);
                $fields = (array)$data;

                if (!empty($files)) {
                    foreach ($files as $key => $file) {
                        $files['file_' . $key] = $file;
                        unset($files[$key]);
                    }
                    $fields = array_merge($fields, $files);
                }

                fputcsv($fp, $fields);
            }
            fclose($fp);
        }
        $this->downloadFile($path, $fileName);
    }

    private function downloadFile($path, $file)
    {
        if (!file_exists($path . $file)) {
            add_action('admin_notices', [$this, 'error_export_notice']);
        } else {
            header('HTTP/1.1 200 OK');
            header('Cache-Control: no-cache, must-revalidate');
            header("Pragma: no-cache");
            header("Expires: 0");
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=$file");
            readfile($path . $file);
            exit;
        }
    }

    function success_export_notice() {
        echo View::render('admin.view.notices.error-export', []);
    }

    function error_export_notice() {
        echo View::render('admin.view.notices.error-export', []);
    }
}
$submissions = new Submissions();
$submissions->init();
