<?php
namespace BLR\Backline\Modules\Outreach;

use BLR\Backline\Core\Access;
use BLR\Backline\Core\CrudHelpers;
use BLR\Backline\Core\ListPage;
use BLR\Backline\Core\Request;
use BLR\Backline\Core\Router;
use BLR\Backline\Core\Views;

if (!defined('ABSPATH')) {
    exit;
}

final class Pages {
    public static function render_list(array $ctx): string {
        $ctx['outreach_list'] = self::list_data($ctx);
        return Views::render('pages/outreach-campaigns', $ctx);
    }

    public static function render_form(array $ctx): string {
        return Views::render('pages/outreach-form', $ctx);
    }

    public static function render_view(array $ctx): string {
        return Views::render('pages/view-outreach', $ctx);
    }

    public static function handle_delete(array $ctx): string {
        return self::handle_post_delete($ctx, 'blr_outreach', 'outreach');
    }

    public static function list_data(array $ctx): array {
        $base = ListPage::base_url($ctx);
        $page_num = Views::current_page_from_query_arg('pg');
        $view_mode = ListPage::view_mode();
        $search_term = Request::query_text('s');
        $status_filter = Request::query_text('status');
        $campaign_statuses = Module::campaign_statuses();

        $query_args = [
            'post_type'      => 'blr_outreach',
            'post_status'    => ['draft', 'publish'],
            'posts_per_page' => 25,
            'paged'          => $page_num,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ];

        if ($search_term !== '') {
            $query_args['s'] = $search_term;
        }

        if ($status_filter !== '' && in_array($status_filter, $campaign_statuses, true)) {
            if ($status_filter === 'Draft') {
                $query_args['post_status'] = ['draft'];
            } elseif (Module::is_valid_campaign_workflow_status($status_filter)) {
                $query_args['meta_query'] = [
                    'relation' => 'OR',
                    [
                        'key'   => 'blr_outreach_workflow_status',
                        'value' => $status_filter,
                    ],
                    [
                        'key'   => 'blr_outreach_status',
                        'value' => $status_filter,
                    ],
                ];
            } else {
                $query_args['meta_query'] = [[
                    'key'   => 'blr_outreach_status',
                    'value' => $status_filter,
                ]];
            }
        }

        $campaigns = new \WP_Query($query_args);
        $campaigns_summary = Views::pagination_summary_data($campaigns, 'pg');

        $persist_args = [];
        if ($search_term !== '') {
            $persist_args['s'] = $search_term;
        }
        if ($status_filter !== '') {
            $persist_args['status'] = $status_filter;
        }

        $campaign_items = [];
        foreach ((array) $campaigns->posts as $post) {
            if (!$post instanceof \WP_Post) {
                continue;
            }

            $post_id = (int) $post->ID;
            $subject = (string) get_post_meta($post_id, 'blr_outreach_subject', true);
            $stats = Module::get_campaign_stats($post_id);
            $status = Module::resolved_campaign_status($post_id, $stats);
            $last_sent = (string) get_post_meta($post_id, 'blr_outreach_last_sent_at', true);

            $campaign_items[] = [
                'id'           => $post_id,
                'title'        => get_the_title($post),
                'subject'      => $subject,
                'stats'        => $stats,
                'status'       => $status,
                'status_badge' => Module::badge($status),
                'last_sent'    => $last_sent,
                'view_url'     => $base . 'outreach/view/' . $post_id . '/',
                'edit_url'     => $base . 'outreach/edit/' . $post_id . '/',
                'delete_url'   => $base . 'outreach/delete/' . $post_id . '/',
            ];
        }

        return array_merge(ListPage::notices(), ListPage::view_urls($base, 'outreach', $persist_args, $view_mode), [
            'base'               => $base,
            'page_num'           => $page_num,
            'search_term'        => $search_term,
            'status_filter'      => $status_filter,
            'view_mode'          => $view_mode,
            'campaign_statuses'  => $campaign_statuses,
            'campaigns'          => $campaigns,
            'campaigns_summary'  => $campaigns_summary,
            'campaign_items'     => $campaign_items,
        ]);
    }

    private static function handle_post_delete(array $ctx, string $post_type, string $section): string {
        $id = (int) ($ctx['id'] ?? 0);
        $redirect_to = rtrim((string) ($ctx['base_url'] ?? Router::base_url()), '/') . '/' . $section . '/?deleted=1';

        if ($id <= 0) {
            CrudHelpers::redirect(add_query_arg(['delete_error' => 'missing_id'], $redirect_to));
            return '';
        }

        if (Request::method() !== 'POST') {
            CrudHelpers::redirect(add_query_arg(['delete_error' => 'invalid_method'], $redirect_to));
            return '';
        }

        $nonce_action = 'blr_ba_delete_' . $post_type . '_' . $id;
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field((string) wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce === '' || !wp_verify_nonce($nonce, $nonce_action)) {
            CrudHelpers::redirect(add_query_arg(['delete_error' => 'invalid_nonce'], $redirect_to));
            return '';
        }

        $post = get_post($id);
        if (!$post instanceof \WP_Post || $post->post_type !== $post_type) {
            return Views::render('pages/404', $ctx);
        }

        if (!Access::can_delete_post($id, $post_type)) {
            CrudHelpers::redirect(add_query_arg(['delete_error' => 'forbidden'], $redirect_to));
            return '';
        }

        if (!wp_delete_post($id, true)) {
            CrudHelpers::redirect(add_query_arg(['delete_error' => 'delete_failed'], $redirect_to));
            return '';
        }

        CrudHelpers::redirect($redirect_to);
        return '';
    }
}
