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

use BLR\Backline\Core\Access;
use BLR\Backline\Core\CrudHelpers;
use BLR\Backline\Core\ListPage;
use BLR\Backline\Core\Money;
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 maybe_handle_form(array $ctx, string $submitted_action): array {
        return $ctx;
    }

    public static function render_list(array $ctx): string {
        $ctx['finances_list'] = self::list_data($ctx);
        return Views::render('pages/finances', $ctx);
    }

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

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

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

        $args = [
            'post_type'      => Module::POST_TYPE,
            'post_status'    => ['publish', 'draft'],
            'posts_per_page' => 25,
            'paged'          => $page_num,
            'meta_key'       => 'blr_finance_date',
            'orderby'        => ['meta_value' => 'DESC', 'date' => 'DESC'],
            'meta_type'      => 'DATE',
        ];

        $meta_query = [];
        if ($kind_filter !== '') {
            $args_kind = Module::normalize_kind($kind_filter);
            if ($args_kind !== '') {
                $meta_query[] = [
                    'key'   => 'blr_finance_kind',
                    'value' => $args_kind,
                ];
            }
        }

        if ($status_filter !== '') {
            $args_status = Module::normalize_status($status_filter);
            if ($args_status !== '') {
                $meta_query[] = [
                    'key'   => 'blr_finance_status',
                    'value' => $args_status,
                ];
            }
        }

        if (!empty($meta_query)) {
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Finance archive intentionally filters by finance meta.
            $args['meta_query'] = $meta_query;
        }

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

        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Finance archive intentionally sorts by finance date meta.
        $records = new \WP_Query($args);
        $summary = Views::pagination_summary_data($records, 'pg');
        $month_totals = Module::month_totals();
        $current_balance = Module::current_balance();
        $overdue_count = Module::overdue_invoices_count();

        $record_items = [];
        foreach ((array) $records->posts as $record) {
            if (!$record instanceof \WP_Post) {
                continue;
            }

            $record_id = (int) $record->ID;
            $kind = (string) get_post_meta($record_id, 'blr_finance_kind', true);
            $status = (string) get_post_meta($record_id, 'blr_finance_status', true);
            $amount = (string) get_post_meta($record_id, 'blr_finance_amount', true);
            $currency = (string) get_post_meta($record_id, 'blr_finance_currency', true);
            $finance_date = (string) get_post_meta($record_id, 'blr_finance_date', true);
            $due_date = (string) get_post_meta($record_id, 'blr_finance_due_date', true);
            $category = (string) get_post_meta($record_id, 'blr_finance_category', true);
            $reference = (string) get_post_meta($record_id, 'blr_finance_reference', true);
            $contact_id = (int) get_post_meta($record_id, 'blr_finance_contact_id', true);

            $record_items[] = [
                'id'            => $record_id,
                'title'         => get_the_title($record),
                'kind'          => $kind,
                'status'        => $status,
                'amount'        => Money::money_label($amount, $currency),
                'finance_date'  => $finance_date,
                'due_date'      => $due_date,
                'category'      => $category,
                'reference'     => $reference,
                'contact_label' => $contact_id > 0 ? Module::contact_label($contact_id) : '',
                'kind_badge'    => Module::badge($kind, 'kind'),
                'status_badge'  => Module::badge($status),
                'view_url'      => $base . 'finances/view/' . $record_id . '/',
                'edit_url'      => $base . 'finances/edit/' . $record_id . '/',
                'delete_url'    => $base . 'finances/delete/' . $record_id . '/',
            ];
        }

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

        $balance_value = (float) $current_balance;
        $balance_class = 'text-body';
        if ($balance_value > 0) {
            $balance_class = 'text-success';
        } elseif ($balance_value < 0) {
            $balance_class = 'text-danger';
        }

        return array_merge(ListPage::notices(), [
            'base'                => $base,
            'page_num'            => $page_num,
            'kind_filter'         => $kind_filter,
            'status_filter'       => $status_filter,
            'search_term'         => $search_term,
            'records'             => $records,
            'summary'             => $summary,
            'month_totals'        => $month_totals,
            'current_balance'     => $current_balance,
            'overdue_count'       => $overdue_count,
            'record_items'        => $record_items,
            'pagination_base_url' => add_query_arg($persist_args, $base . 'finances/'),
            'balance_value'       => $balance_value,
            'balance_class'       => $balance_class,
        ]);
    }

    public static function handle_delete(array $ctx): string {
        $id = (int) ($ctx['id'] ?? 0);
        if ($id <= 0) {
            return self::render_not_found();
        }

        $request_method = Request::method();
        if ($request_method !== 'POST') {
            return self::render_not_found();
        }

        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field((string) wp_unslash($_POST['_wpnonce'])) : '';
        $nonce_action = 'blr_ba_delete_blr_finance_record_' . $id;
        if ($nonce === '' || !wp_verify_nonce($nonce, $nonce_action)) {
            return self::render_not_found();
        }

        $post = get_post($id);
        if (
            !$post instanceof \WP_Post ||
            $post->post_type !== Module::POST_TYPE ||
            !Access::can_delete_post($id, Module::POST_TYPE)
        ) {
            return self::render_not_found();
        }

        $deleted = wp_delete_post($id, true);
        if (!$deleted) {
            return self::render_not_found();
        }

        $base = trailingslashit((string) ($ctx['base_url'] ?? Router::base_url()));
        CrudHelpers::redirect($base . 'finances/?deleted=1');
        return '';
    }

    public static function render_not_found(): string {
        return Views::render('pages/404', []);
    }
}
