<?php
/**
 * Contact Requests View
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Admin;

use _121Digital\Connect\Integration\ContactForms;

/**
 * ContactRequestsView Class
 *
 * Handles the admin page for viewing contact form submissions
 */
class ContactRequestsView
{
    /**
     * ContactForms instance
     *
     * @var ContactForms
     */
    private ContactForms $contactForms;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->contactForms = new ContactForms();
    }

    /**
     * Register menu page hooks
     *
     * @return void
     */
    public function register(): void
    {
        add_action('admin_menu', [$this, 'addMenuPage']);
    }

    /**
     * Add menu page
     *
     * @return void
     */
    public function addMenuPage(): void
    {
        add_menu_page(
            'Contact Requests',
            'Contact Requests',
            'edit_posts',
            'sc-contact-requests',
            [$this, 'renderListView'],
            'dashicons-welcome-view-site',
            26
        );

        // Hidden page for viewing individual contact request
        add_submenu_page(
            '',
            'View Contact Request',
            'View Contact Request',
            'edit_posts',
            'sc-contact-requests-view',
            [$this, 'renderDetailView']
        );
    }

    /**
     * Generate URL for viewing a contact request
     *
     * @param array $entry
     * @return string
     */
    private function generateViewContactUrl(array $entry): string
    {
        $encodedEntry = $this->contactForms->encodeUrlParams($entry);
        $adminUrl = admin_url('admin.php?page=sc-contact-requests-view&e=' . $encodedEntry);

        return esc_url($adminUrl);
    }

    /**
     * Render list view of all contact requests
     *
     * @return void
     */
    public function renderListView(): void
    {
        if (!current_user_can('edit_posts')) {
            wp_die(__('You do not have permission to access this page.'));
        }

        $contactRequests = $this->contactForms->getSubmissions();

        ?>
        <div class="wrap">
            <h1>Contact Requests</h1>
            <p style='margin: 0; padding: 0;'>Contact requests that have been submitted by your website's visitors.</p>

            <table class="wp-list-table widefat fixed striped" style='max-width: 1200px;'>
                <thead>
                    <tr>
                        <th scope="col"><b>ID</b></th>
                        <th scope="col"><b>Date</b></th>
                        <th scope="col"><b>Contact Info</b></th>
                        <th scope='col'></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($contactRequests)) : ?>
                        <tr>
                            <td colspan="4">No contact requests found.</td>
                        </tr>
                    <?php else : ?>
                        <?php foreach ($contactRequests as $request) : ?>
                            <tr>
                                <td><?php echo esc_html($request['entry_id']); ?></td>
                                <td><?php echo esc_html(date('Y-m-d H:i:s', strtotime($request['entry_date']))); ?></td>
                                <td><?php echo esc_html($this->contactForms->getEntryFromInfo($request)); ?></td>
                                <td style='text-align: right;'>
                                    <a href='<?php echo $this->generateViewContactUrl($request); ?>' class='button' style='text-align: right;'>
                                        View Submission
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    /**
     * Make field name readable
     *
     * @param string $str
     * @return string
     */
    private function makeReadableFieldName(string $str): string
    {
        $str = preg_replace('/^mf-/', '', $str);
        $str = str_replace('-', ' ', $str);
        return ucwords($str);
    }

    /**
     * Render a row in the detail view
     *
     * @param string $rowKey
     * @param mixed $rowValue
     * @return void
     */
    private function renderDetailRow(string $rowKey, $rowValue): void
    {
        if ($rowKey == 'entry_id') {
            return;
        }

        echo "<tr style='max-width: 600px;'>";
        echo '<td>' . $this->makeReadableFieldName($rowKey) . '</td>';
        echo '<td>';

        if ($rowKey == 'mf-comment') {
            echo "<textarea disabled class='regular-text' style='width: 100%; height: 100px; color: black !important;'>" . esc_textarea($rowValue) . '</textarea>';
        } else {
            echo "<input disabled value='" . esc_attr($rowValue) . "' class='regular-text' style='width: 100%; color: black !important;' type='text'>";
        }

        echo '</td>';
        echo '</tr>';
    }

    /**
     * Render detail view of a single contact request
     *
     * @return void
     */
    public function renderDetailView(): void
    {
        if (!current_user_can('edit_posts')) {
            wp_die(__('You do not have permission to access this page.'));
        }

        if (!isset($_GET['e']) || empty($_GET['e'])) {
            wp_die(__('No contact request ID provided.'));
        }

        $encodedEntry = $_GET['e'];
        $decodedEntry = $this->contactForms->decodeUrlParams($encodedEntry);
        $entry = $this->contactForms->getEntry($decodedEntry);

        ?>
        <div class="wrap">
            <h1>View Contact Request</h1>
            <div class="wp-toolbar" style="margin-bottom: 20px;">
                <a href="<?php echo esc_url(admin_url('admin.php?page=sc-contact-requests')); ?>" class="button button-secondary">
                    &larr; Back to Contact Requests
                </a>
            </div>

            <table class="wp-list-table widefat fixed striped" style='max-width: 600px;'>
                <?php foreach ($entry as $rowKey => $rowValue) : ?>
                    <?php $this->renderDetailRow($rowKey, $rowValue); ?>
                <?php endforeach; ?>
            </table>
        </div>
        <?php
    }
}
