<?php

namespace auctionforge\inc\shortcodes;

use auctionforge\inc\abs\BidspiritWebhooks;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\SubmissionFormData;
use auctionforge\inc\traits\LoggerInfo;
use WP_Error;
use WP_REST_Request;
use WP_REST_Server;

class SubmissionForm extends BidspiritWebhooks
{
    use LoggerInfo;

    protected $fields = [
        'year' => [
            'type' => 'number',
            'label' => 'Year of registration (Year on the road)',
            'short_label' => 'Year of registration',
            'required' => true,
            'notice' => 'This field is required and should be number'
        ],
        'manufacturer' => [
            'type' => 'text',
            'label' => 'Manufacturer',
            'short_label' => 'Manufacturer',
            'required' => true,
            'options' => [
                'option1' => 'Option 1',
                'option2' => 'Option 2',
                'option3' => 'Option 3',
            ]
        ],
        'model' => [
            'type' => 'text',
            'label' => 'Car model',
            'short_label' => 'Car model',
            'required' => true,
            'options' => [
                'option1' => 'Option 1',
                'option2' => 'Option 2',
                'option3' => 'Option 3',
            ]
        ],
        'kilometers' => [
            'type' => 'number',
            'label' => 'Kilometers (Mileage)',
            'short_label' => 'Kilometers',
            'required' => true,
            'notice' => 'This field is required and should be number'
        ],
        'car_location' => [
            'type' => 'text',
            'label' => 'Where is the car located?',
            'short_label' => 'located',
            'required' => true,
        ],
        'car_in_auctioned' => [
            'type' => 'radio',
            'label' => 'Has the car already been put to auction? Car Already Auctioned?',
            'short_label' => 'Is Auctioned',
            'required' => true,
            'options' => [
                'no' => 'No',
                'yes' => 'Yes',
            ]
        ],
        'video' => [
            'type' => 'text',
            'label' => 'Video (Paste Links)',
            'short_label' => 'Video',
            'required' => true,
        ],
        'you_seller' => [
            'type' => 'radio',
            'label' => 'Are you a seller? / Are you a dealer?',
            'short_label' => 'Is seller',
            'required' => true,
            'options' => [
                'no' => 'No',
                'yes' => 'Yes',
            ]
        ],
        'car_pics' => [
            'type' => 'file',
            'label' => 'Load vehicle images / upload car pics',
            'short_label' => 'Load vehicle images',
            'required' => true,
        ],
        'original_engine' => [
            'type' => 'radio',
            'label' => 'Original engine',
            'short_label' => 'Engine',
            'required' => true,
            'options' => [
                'no' => 'No',
                'yes' => 'Yes',
            ]
        ],
        'transmission' => [
            'type' => 'select',
            'label' => 'Transmission',
            'short_label' => 'Transmission',
            'required' => true,
            'options' => [
                'option1' => 'Option 1',
                'option2' => 'Option 2',
                'option3' => 'Option 3',
            ]
        ],
        'car_documents' => [
            'type' => 'file',
            'label' => 'Load Auto / Upload Car Documents documents',
            'short_label' => 'Load Auto',
            'required' => true,
        ],
        'description' => [
            'type' => 'textarea',
            'label' => 'Vehicle description Note / Descirbe Your Vehicle (Any Editation, Original Parts)',
            'short_label' => 'Vehicle description',
            'required' => true,
        ],
        'service' => [
            'type' => 'text',
            'label' => 'Revisions / Car Service',
            'short_label' => 'Revisions',
            'required' => true,
        ],
        'reserve' => [
            'type' => 'radio',
            'label' => 'Do you want a reserve price? / Do you want to reserve?',
            'short_label' => 'Is reserve',
            'required' => true,
            'options' => [
                'no' => 'No',
                'yes' => 'Yes',
            ]
        ],
        'notes' => [
            'type' => 'textarea',
            'label' => 'Additional notes',
            'short_label' => 'Notes',
            'required' => true
        ],
    ];

    public function init()
    {
        add_action('rest_api_init', array($this, 'form_data'));

        add_shortcode('bp_submission_form', array($this, 'bp_submission_form'));

        add_action('bp_submission_form_action', [$this, 'bp_submission_form_action']);

        add_action('wp_footer', [$this, 'bp_footer'], 99);
    }

    public function form_data()
    {
        if (!defined('ABSPATH')) {
            die('You shouldnt be here');
        }

        $namespace = self::API_NAMESPACE;

        $rout = '/submission/form';

        $rout_params = array(
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => array($this, 'event_form'),
            'permission_callback' => function ($request) {
                return $this->checkNoncePermissionDefault($request);
            },
        );

        register_rest_route($namespace, $rout, $rout_params);
    }

    public function event_form(WP_REST_Request $request)
    {
        $data = $request->get_params();
        $request->get_file_params();

        $files = $this->fileUploader($request->get_file_params());
        $data['files'] = $this->filesUrl($files);

        $result = SubmissionFormData::save($data);

        if (!$result) {
            $this->removeFiles($files);
        }

        return [
            'result' => $result,
            'data' => $data,
            'response' => $request->get_params(),
            'request' => $request,
        ];
    }

    public function bp_submission_form()
    {
        $data = [
            "name" => "bp_short_register_form"
        ];

        $sourceVersion = "0.1.0";
        $ext = ".min.js";
        if (WP_DEBUG) {
            $sourceVersion = time();
            $ext = ".js";
        }

        wp_enqueue_style('bp_submissions',plugin_dir_url( __FILE__ ).'../../assets/css/submissions.css', ['bitspirit_frontend_libs_style'], $sourceVersion, 'all');

        wp_enqueue_script('bp_submissions_form',
            plugin_dir_url(__FILE__).'../../assets/js/submissions-form'.$ext,
            ['jquery', 'bitspirit_front_app'],
            $sourceVersion,
            [
                'in_footer' => true,
                'strategy' => 'defer',
            ]
        );

        do_action('bp_submission_form_action', $data);
    }

    public function bp_submission_form_action()
    {
        echo View::render('templates/shortcodes/submission-form', [
            'fields' => $this->getFields()
        ]);
    }

    public function bp_footer()
    {
        $fields = $this->getFields();
        echo View::render('templates/js-chunks/submissions', apply_filters('bp_footer_submissions_template_data', array(
            'fields' => $fields
        )));
    }

    public function getFields(): array
    {
        $fields = $this->fields;

        if (!empty($fields)) {
            foreach ($fields as $key => $field) {
                if (isset($field['required']) && $field['required']) {
                    $field['label'] .= "&nbsp;*";
                }

                if (!isset($field['notice'])) {
                    $field['notice'] = __('Field is required', 'auctionforge');
                }
                $fields[$key] = $field;
            }
        }

        return $fields;
    }

    /*public function setFields(array $fields): void
    {
        $this->fields = $fields;
    }*/
    private function fileUploader($fields)
    {
        $uploadedFiles = [];
        $keys = array_keys($fields);
        if (!empty($keys[0]) && !empty($fields[$keys[0]]['name'][0])) {
            require_once(ABSPATH.'wp-admin/includes/file.php');
            require_once(ABSPATH.'wp-admin/includes/image.php');

            $allowed_types = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'docx']; // допустимые типы файлов

            foreach ($fields as $files) {
                foreach ($files['name'] as $key => $file_name) {
                    if ($files['error'][$key] === UPLOAD_ERR_OK) {
                        $file_type = wp_check_filetype($file_name);
                        if (in_array($file_type['ext'], $allowed_types)) {
                            $file = [
                                'name' => $files['name'][$key],
                                'type' => $files['type'][$key],
                                'tmp_name' => $files['tmp_name'][$key],
                                'error' => $files['error'][$key],
                                'size' => $files['size'][$key],
                            ];

                            $upload_overrides = ['test_form' => false];

                            $movefile = wp_handle_upload($file, $upload_overrides);

                            if ($movefile && !isset($movefile['error'])) {
                                $attachment_data = [
                                    'post_mime_type' => $file_type['type'],
                                    'post_title' => sanitize_file_name($file_name),
                                    'post_content' => '',
                                    'post_status' => 'inherit',
                                ];

                                $attachment_id = wp_insert_attachment($attachment_data, $movefile['file']);
                                $attach_data = wp_generate_attachment_metadata($attachment_id, $movefile['file']);
                                $fileResult = wp_update_attachment_metadata($attachment_id, $attach_data);

                                $uploadedFiles[$attachment_id]['data'] = $attach_data;
                                $uploadedFiles[$attachment_id]['res'] = $fileResult;
                            } else {
                                // echo 'Error ' . esc_html($file_name) . ': ' . esc_html($movefile['error']) . '<br>';
                            }
                        } else {
                            // echo 'Unacceptable file type: ' . esc_html($file_name) . '<br>';
                        }
                    } else {
                        // echo 'Error: ' . esc_html($file_name) . '<br>';
                    }
                }
            }
        } else {
            // echo 'Error.';
        }

        return $uploadedFiles;
    }

    private function removeFiles(array $files)
    {
        if (!empty($files)) {
            foreach ($files as $key => $file) {
                wp_delete_attachment($key);
            }
        }
    }

    private function filesUrl(array $files): array
    {
        $urls = [];
        if (!empty($files)) {
            foreach ($files as $key => $file) {
                $urls[] = wp_get_attachment_url($key);
            }
        }

        return $urls;
    }
}

$instance = new SubmissionForm();
$instance->init();
