<?php

namespace RtmMail\Pages;

use RtmMail\Helpers\LogHelper;

/**
 * Details - handles every user interaction for the details page
 */
class Details extends BasePage
{
    protected string $slug = 'details';
    private array $mail_log = [];


    public function __construct(string $mail_capability)
    {
        parent::__construct(
            pageId: 'rtm-mail-details',
            menuSlug: 'rtm-mail-details',
            title: __('Details', 'rtm-mail'),
            parent: 'rtm-mail-main-menu',
            capability: $mail_capability // so it doesn't show, but can still load
        );
    }
    public function doEnqueue(): void {
        parent::doEnqueue();
        wp_enqueue_script('details-script', RTM_MAIL_PLUGIN_URL . 'dist/details.js', [], false, true);
        $this->localizeScript('details-script');
    }

    /**
     * Init - every page can handle their requests (post/get)
     */
    public function init(): void
    {
        parent::init();

        if (isset($_GET['log_id'])) {
            // sanitize the log_id
            $log_id = sanitize_key($_GET['log_id']);
            // Get the log by the log_id and set it to the current log item
            $this->mail_log = LogHelper::get([
                'post_per_page' => null,
                'where'         => [
                    'id' => [
                        'type'  => '=',
                        'value' => $log_id,
                    ]
                ]
            ]);
            // Check if the mail preview is requested
            if (isset($_GET['mail_preview']) && filter_var($_GET['mail_preview'], FILTER_VALIDATE_BOOLEAN)) {
                global $log;
                // set global $log to the current loaded log item
                $log = $this->mail_log;
                require_once RTM_MAIL_PLUGIN_PATH . 'src/Views/preview.php';
                // Don't render anymore
                exit();
            }
        }
    }

    public function renderPage(): void
    {
        $log      = $this->mail_log;
        $settings = get_option('rtm_mail_settings');

        include RTM_MAIL_PLUGIN_PATH . 'src/Views/' . $this->slug . '.php';
    }
}
