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

class BMTQB_Submission_Details {
    private $industries = [];
    private $integration_manager;

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

    public function register(BMTQB_Industry_Interface $industry) {
        $this->industries[$industry->post_type()] = $industry;

        add_action('add_meta_boxes', function () use ($industry) {
            add_meta_box(
                $industry->meta_prefix() . '_submission_details',
                'Submission Details',
                [$this, 'render_submission_details'],
                $industry->post_type(),
                'normal',
                'high'
            );
        });
    }

    public function render_submission_details($post) {
        $industry = $this->industries[$post->post_type] ?? null;
        if (!$industry) {
            return;
        }

        $prefix = $industry->meta_prefix();
        $form_data = get_post_meta($post->ID, '_' . $prefix . '_form_data', true);
        $results = get_post_meta($post->ID, '_' . $prefix . '_results', true);
        $status = get_post_meta($post->ID, '_' . $prefix . '_status', true);
        $pdf_path = get_post_meta($post->ID, '_' . $prefix . '_pdf_path', true);
        $pdf_error = get_post_meta($post->ID, '_' . $prefix . '_pdf_error', true);
        $email_status = get_post_meta($post->ID, '_' . $prefix . '_email_status', true);
        $email_error = get_post_meta($post->ID, '_' . $prefix . '_email_error', true);
        $photos = get_post_meta($post->ID, '_' . $prefix . '_photos', true);
        $photo_error = get_post_meta($post->ID, '_' . $prefix . '_photo_error', true);

        $form_data = is_array($form_data) ? $form_data : [];
        $results = is_array($results) ? $results : [];

        echo '<style>
            .bmtqb-admin-grid { display:grid; grid-template-columns:1fr 1fr; gap:24px; }
            .bmtqb-admin-box { background:#fff; border:1px solid #ddd; padding:16px; }
            .bmtqb-admin-box h3 { margin-top:0; }
            .bmtqb-admin-row { padding:6px 0; border-bottom:1px solid #eee; }
            .bmtqb-admin-row strong { display:inline-block; min-width:180px; }
            .bmtqb-admin-list { margin:8px 0 0 18px; }
            .bmtqb-admin-photos { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; margin-top:8px; }
            .bmtqb-admin-photo img { max-width:100%; height:auto; border:1px solid #ddd; background:#fff; }
            .bmtqb-admin-photo-label { font-weight:600; margin-bottom:4px; }
            @media (max-width: 900px) {
                .bmtqb-admin-grid { grid-template-columns:1fr; }
                .bmtqb-admin-photos { grid-template-columns:1fr; }
            }
        </style>';

        echo '<div class="bmtqb-admin-grid">';

        echo '<div class="bmtqb-admin-box">';
        echo '<h3>Customer & Form Answers</h3>';
        $this->row('Status', $status ?: 'new');
        $this->row('Quote ID', $industry->stored_quote_reference($post->ID));
        $this->row('First Name', $form_data['first_name'] ?? '');
        $this->row('Last Name', $form_data['last_name'] ?? '');
        $this->row('Email', $form_data['email'] ?? '');
        $this->row('Phone', $form_data['phone'] ?? '');
        $this->row('Service Address', $form_data['service_address'] ?? '');
        $this->row('Consent To Contact', !empty($form_data['consentToContact']) ? 'Yes' : 'No');

        echo '<hr>';
        foreach ($industry->admin_answer_rows($form_data, $results, $post->ID) as $row) {
            $this->row($row['label'] ?? '', $row['value'] ?? '');
        }

        $pdf_link = '';
        if ($pdf_path) {
            $pdf_url = BMTQB_Formatter::pdf_url_from_path($pdf_path);
            $pdf_link = '<a href="' . esc_url($pdf_url) . '" target="_blank">View PDF</a><br><small>' . esc_html($pdf_path) . '</small>';
        }

        $this->row('PDF', $pdf_link);
        $this->row('PDF Error', $pdf_error ?: '');
        $this->row('Email Status', $email_status ?: '');
        $this->row('Email Error', $email_error ?: '');
        $this->row('Photo Error', $photo_error ?: '');
        $this->render_photos($photos);
        echo '</div>';

        echo '<div class="bmtqb-admin-box">';
        echo '<h3>Calculated Results</h3>';
        foreach ($industry->admin_result_rows($form_data, $results, $post->ID) as $row) {
            $this->row($row['label'] ?? '', $row['value'] ?? '');
        }
        $this->render_review_flags($results['reviewFlags'] ?? []);
        $this->render_integrations($industry, $post->ID);
        echo '</div>';

        echo '</div>';
    }

    private function render_photos($photos) {
        echo '<div class="bmtqb-admin-row"><strong>Uploaded Photos</strong><div>';
        if (!empty($photos) && is_array($photos)) {
            echo '<div class="bmtqb-admin-photos">';
            foreach ($photos as $photo) {
                $label = $photo['label'] ?? 'Photo';
                $url = $photo['url'] ?? '';
                if ($url === '') {
                    continue;
                }
                echo '<div class="bmtqb-admin-photo"><div class="bmtqb-admin-photo-label">' . esc_html($label) . '</div>';
                echo '<a href="' . esc_url($url) . '" target="_blank" rel="noopener"><img src="' . esc_url($url) . '" alt="' . esc_attr($label) . '"></a></div>';
            }
            echo '</div>';
        } else {
            echo 'No photos uploaded';
        }
        echo '</div></div>';
    }

    private function render_review_flags($flags) {
        echo '<div class="bmtqb-admin-row"><strong>Review Flags</strong><div>';
        if (!empty($flags) && is_array($flags)) {
            echo '<ul class="bmtqb-admin-list">';
            foreach ($flags as $flag) {
                echo '<li>' . esc_html($flag) . '</li>';
            }
            echo '</ul>';
        } else {
            echo 'None';
        }
        echo '</div></div>';
    }

    private function render_integrations(BMTQB_Industry_Interface $industry, $post_id) {
        $sections = $this->integration_manager->admin_sections($industry, $post_id);

        echo '<hr>';
        echo '<h3>Integrations</h3>';

        if (empty($sections)) {
            echo '<div class="bmtqb-admin-row"><strong>Status</strong> <span>No integrations registered.</span></div>';
            return;
        }

        foreach ($sections as $section) {
            echo '<h4>' . esc_html($section['label'] ?? 'Integration') . '</h4>';
            foreach (($section['rows'] ?? []) as $row) {
                $this->row($row['label'] ?? '', $row['value'] ?? '');
            }
        }
    }

    private function row($label, $value) {
        echo '<div class="bmtqb-admin-row">';
        echo '<strong>' . esc_html($label) . '</strong> ';
        echo '<span>' . wp_kses_post((string) $value) . '</span>';
        echo '</div>';
    }
}
