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

class BMTQB_Submission_Controller {
    private $integration_manager;

    public function __construct(BMTQB_Integration_Manager $integration_manager) {
        $this->integration_manager = $integration_manager;
    }

    public function register(BMTQB_Industry_Interface $industry) {
        add_action('wp_ajax_' . $industry->ajax_action(), function () use ($industry) {
            $this->submit($industry);
        });
        add_action('wp_ajax_nopriv_' . $industry->ajax_action(), function () use ($industry) {
            $this->submit($industry);
        });
    }

    private function submit(BMTQB_Industry_Interface $industry) {
        check_ajax_referer($industry->nonce_action(), 'nonce');

        $raw = $_POST['data'] ?? [];
        $data = $industry->sanitize_submission($raw);

        $validation = $industry->validate_submission($data);
        if (is_wp_error($validation)) {
            wp_send_json_error(['message' => $validation->get_error_message()]);
        }

        if (empty($data['consentToContact'])) {
            wp_send_json_error(['message' => 'Please agree to the consent checkbox before submitting your quote.']);
        }

        $photo_validation = BMTQB_Photo_Uploader::validate_request($industry, $_FILES);
        if (is_wp_error($photo_validation)) {
            wp_send_json_error(['message' => $photo_validation->get_error_message()]);
        }

        $results = $industry->calculate($data);
        $prefix = $industry->meta_prefix();

        $post_id = wp_insert_post([
            'post_type' => $industry->post_type(),
            'post_status' => 'publish',
            'post_title' => $industry->submission_title($data),
        ], true);

        if (is_wp_error($post_id)) {
            wp_send_json_error(['message' => 'Could not save submission.']);
        }

        $quote_reference = $industry->quote_reference($post_id);

        update_post_meta($post_id, '_' . $prefix . '_form_data', $data);
        update_post_meta($post_id, '_' . $prefix . '_results', $results);
        update_post_meta($post_id, '_' . $prefix . '_email', $data['email'] ?? '');
        update_post_meta($post_id, '_' . $prefix . '_phone', $data['phone'] ?? '');
        update_post_meta($post_id, '_' . $prefix . '_service_address', $data['service_address'] ?? '');
        update_post_meta($post_id, '_' . $prefix . '_status', 'new');
        update_post_meta($post_id, '_' . $prefix . '_quote_reference', $quote_reference);

        $photos = BMTQB_Photo_Uploader::handle_uploads($industry, $post_id, $_FILES);
        if (is_wp_error($photos)) {
            update_post_meta($post_id, '_' . $prefix . '_photo_error', $photos->get_error_message());
            wp_send_json_error([
                'message' => $photos->get_error_message(),
                'post_id' => $post_id,
            ]);
        }

        $photos_sent = !empty($photos) && is_array($photos);
        $settings = BMTQB_Settings_Repository::all($industry);
        $results_message = $industry->results_message($settings, $photos_sent);
        $results_actions = [];

        $pdf_path = '';
        $pdf_url = '';

        try {
            $pdf_path = BMTQB_PDF_Service::generate($industry, $data, $results, $post_id, $photos);

            if (!empty($pdf_path)) {
                update_post_meta($post_id, '_' . $prefix . '_pdf_path', $pdf_path);
                $email_result = BMTQB_Email_Service::send($industry, $data, $pdf_path, $photos, $results, $quote_reference);

                if (is_wp_error($email_result)) {
                    update_post_meta($post_id, '_' . $prefix . '_email_error', $email_result->get_error_message());
                } else {
                    update_post_meta($post_id, '_' . $prefix . '_email_status', 'sent');
                }
            }

            $pdf_url = BMTQB_Formatter::pdf_url_from_path($pdf_path);
            $results_actions = $industry->results_actions($settings, $photos_sent, $pdf_url);
        } catch (Throwable $e) {
            update_post_meta($post_id, '_' . $prefix . '_pdf_error', $e->getMessage());
        }

        $integration_results = $this->integration_manager->dispatch(new BMTQB_Integration_Context(
            $industry,
            $data,
            $results,
            $post_id,
            $pdf_path,
            $photos,
            $quote_reference
        ));

        $response = [
            'message' => 'Submission saved successfully.',
            'post_id' => $post_id,
            'results' => $results,
            'pdf_path' => $pdf_path,
            'pdf_url' => $pdf_url,
            'results_message' => apply_filters('the_content', $results_message),
            'results_actions' => $results_actions,
            'photos_sent' => $photos_sent,
            'quote_reference' => $quote_reference,
            'integrations' => $integration_results,
        ];

        $response = array_merge($response, $industry->response_data($data, $results, $post_id, $pdf_path, $photos));

        wp_send_json_success($response);
    }
}
