<?php
namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\ClientService;

defined('ABSPATH') || exit;

class ClientsScreen {

    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }

        self::handleActions();

        $action = isset($_GET['action']) ? sanitize_key($_GET['action']) : 'list';

        echo '<div class="wrap">';
        echo '<h1 class="wp-heading-inline">' . esc_html__('Clients', 'comptaflow-uk-by-meetempo') . '</h1>';

        if ($action === 'list') {
            echo '<a href="?page=comptaflow-uk-clients&action=new" class="page-title-action">' . esc_html__('Add New Client', 'comptaflow-uk-by-meetempo') . '</a>';
        }

        settings_errors('comptaflow_uk_clients');

        if ($action === 'new' || $action === 'edit') {
            self::renderForm($action);
        } else {
            self::renderList();
        }

        echo '</div>';
    }

    private static function handleActions(): void {
        if (!isset($_POST['_wpnonce'])) {
            if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
                $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
                if (wp_verify_nonce($nonce, 'comptaflow_uk_delete_client')) {
                    ClientService::delete(absint($_GET['id']));
                    add_settings_error('comptaflow_uk_clients', 'deleted', __('Client deleted.', 'comptaflow-uk-by-meetempo'), 'updated');
                }
            }
            return;
        }

        $nonce = sanitize_text_field(wp_unslash($_POST['_wpnonce']));
        if (!wp_verify_nonce($nonce, 'comptaflow_uk_client_save')) {
            return;
        }

        $data = [
            'client_type' => isset($_POST['client_type']) ? sanitize_text_field(wp_unslash($_POST['client_type'])) : 'COMPANY',
            'company_name' => isset($_POST['company_name']) ? sanitize_text_field(wp_unslash($_POST['company_name'])) : '',
            'contact_name' => isset($_POST['contact_name']) ? sanitize_text_field(wp_unslash($_POST['contact_name'])) : '',
            'email' => isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '',
            'phone' => isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : '',
            'address_line_1' => isset($_POST['address_line_1']) ? sanitize_text_field(wp_unslash($_POST['address_line_1'])) : '',
            'address_line_2' => isset($_POST['address_line_2']) ? sanitize_text_field(wp_unslash($_POST['address_line_2'])) : '',
            'city' => isset($_POST['city']) ? sanitize_text_field(wp_unslash($_POST['city'])) : '',
            'county' => isset($_POST['county']) ? sanitize_text_field(wp_unslash($_POST['county'])) : '',
            'postcode' => isset($_POST['postcode']) ? sanitize_text_field(wp_unslash($_POST['postcode'])) : '',
            'country' => isset($_POST['country']) ? sanitize_text_field(wp_unslash($_POST['country'])) : 'GB',
            'company_number' => isset($_POST['company_number']) ? sanitize_text_field(wp_unslash($_POST['company_number'])) : '',
            'vat_number' => isset($_POST['vat_number']) ? sanitize_text_field(wp_unslash($_POST['vat_number'])) : '',
            'payment_terms' => isset($_POST['payment_terms']) ? absint($_POST['payment_terms']) : 30,
            'notes' => isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '',
        ];

        $id = isset($_POST['client_id']) ? absint($_POST['client_id']) : 0;
        if ($id) {
            ClientService::update($id, $data);
            add_settings_error('comptaflow_uk_clients', 'updated', __('Client updated.', 'comptaflow-uk-by-meetempo'), 'updated');
        } else {
            ClientService::create($data);
            add_settings_error('comptaflow_uk_clients', 'created', __('Client created.', 'comptaflow-uk-by-meetempo'), 'updated');
        }
    }

    private static function renderForm(string $action): void {
        $client = [];
        if ($action === 'edit' && isset($_GET['id'])) {
            $client = ClientService::getById(absint($_GET['id']));
        }

        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit Client', 'comptaflow-uk-by-meetempo') : esc_html__('New Client', 'comptaflow-uk-by-meetempo')) . '</h2>';
        echo '<form method="post">';
        wp_nonce_field('comptaflow_uk_client_save');
        if (!empty($client['id'])) {
            echo '<input type="hidden" name="client_id" value="' . esc_attr($client['id']) . '">';
        }

        echo '<table class="form-table">';

        echo '<tr><th>' . esc_html__('Type', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<select name="client_type">';
        echo '<option value="COMPANY"' . selected($client['client_type'] ?? 'COMPANY', 'COMPANY', false) . '>' . esc_html__('Company', 'comptaflow-uk-by-meetempo') . '</option>';
        echo '<option value="INDIVIDUAL"' . selected($client['client_type'] ?? '', 'INDIVIDUAL', false) . '>' . esc_html__('Individual', 'comptaflow-uk-by-meetempo') . '</option>';
        echo '</select></td></tr>';

        $fields = [
            'company_name' => __('Company Name', 'comptaflow-uk-by-meetempo'),
            'contact_name' => __('Contact Name', 'comptaflow-uk-by-meetempo'),
            'email' => __('Email', 'comptaflow-uk-by-meetempo'),
            'phone' => __('Phone', 'comptaflow-uk-by-meetempo'),
            'address_line_1' => __('Address Line 1', 'comptaflow-uk-by-meetempo'),
            'address_line_2' => __('Address Line 2', 'comptaflow-uk-by-meetempo'),
            'city' => __('City', 'comptaflow-uk-by-meetempo'),
            'county' => __('County', 'comptaflow-uk-by-meetempo'),
            'postcode' => __('Postcode', 'comptaflow-uk-by-meetempo'),
            'company_number' => __('Company Number', 'comptaflow-uk-by-meetempo'),
            'vat_number' => __('VAT Number', 'comptaflow-uk-by-meetempo'),
        ];

        foreach ($fields as $key => $label) {
            $type = ($key === 'email') ? 'email' : 'text';
            echo '<tr><th><label for="' . esc_attr($key) . '">' . esc_html($label) . '</label></th>';
            echo '<td><input type="' . esc_attr($type) . '" id="' . esc_attr($key) . '" name="' . esc_attr($key) . '" value="' . esc_attr($client[$key] ?? '') . '" class="regular-text"></td></tr>';
        }

        echo '<tr><th>' . esc_html__('Payment Terms (days)', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<td><input type="number" name="payment_terms" value="' . esc_attr($client['payment_terms'] ?? 30) . '" min="0" style="width:80px"></td></tr>';

        echo '<tr><th>' . esc_html__('Notes', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<td><textarea name="notes" rows="3" class="large-text">' . esc_textarea($client['notes'] ?? '') . '</textarea></td></tr>';

        echo '</table>';
        submit_button($action === 'edit' ? esc_html__('Update Client', 'comptaflow-uk-by-meetempo') : esc_html__('Create Client', 'comptaflow-uk-by-meetempo'));
        echo '</form>';
    }

    private static function renderList(): void {
        $search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
        $page_num = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
        $per_page = 20;
        $offset = ($page_num - 1) * $per_page;

        $clients = ClientService::getAll(0, $search, $per_page, $offset);
        $total = ClientService::count(0, $search);

        echo '<form method="get">';
        echo '<input type="hidden" name="page" value="comptaflow-uk-clients">';
        echo '<p class="search-box">';
        echo '<input type="search" name="s" value="' . esc_attr($search) . '" placeholder="' . esc_attr__('Search clients...', 'comptaflow-uk-by-meetempo') . '">';
        echo '<input type="submit" class="button" value="' . esc_attr__('Search', 'comptaflow-uk-by-meetempo') . '">';
        echo '</p>';
        echo '</form>';

        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Name', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Contact', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Email', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('City', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Actions', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '</tr></thead><tbody>';

        if (empty($clients)) {
            echo '<tr><td colspan="5">' . esc_html__('No clients found.', 'comptaflow-uk-by-meetempo') . '</td></tr>';
        }

        foreach ($clients as $c) {
            $edit_url = admin_url('admin.php?page=comptaflow-uk-clients&action=edit&id=' . $c['id']);
            $delete_url = wp_nonce_url(
                admin_url('admin.php?page=comptaflow-uk-clients&action=delete&id=' . $c['id']),
                'comptaflow_uk_delete_client'
            );
            $name = ClientService::getDisplayName($c);

            echo '<tr>';
            echo '<td><strong><a href="' . esc_url($edit_url) . '">' . esc_html($name) . '</a></strong></td>';
            echo '<td>' . esc_html($c['contact_name'] ?? '') . '</td>';
            echo '<td>' . esc_html($c['email'] ?? '') . '</td>';
            echo '<td>' . esc_html($c['city'] ?? '') . '</td>';
            echo '<td>';
            echo '<a href="' . esc_url($edit_url) . '">' . esc_html__('Edit', 'comptaflow-uk-by-meetempo') . '</a> | ';
            echo '<a href="' . esc_url($delete_url) . '" onclick="return confirm(\'' . esc_js(__('Delete this client?', 'comptaflow-uk-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-uk-by-meetempo') . '</a>';
            echo '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';

        $total_pages = ceil($total / $per_page);
        if ($total_pages > 1) {
            echo '<div class="tablenav"><div class="tablenav-pages">';
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links returns safe HTML
            echo paginate_links([
                'base' => add_query_arg('paged', '%#%'),
                'format' => '',
                'current' => $page_num,
                'total' => $total_pages,
            ]);
            echo '</div></div>';
        }
    }
}
