<?php
/**
 * ComptaFlow - Ecran de gestion des clients
 */

namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\ClientService;

defined('ABSPATH') || exit;

class ClientsScreen {

    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Access denied.', 'comptaflow-by-meetempo'));
        }

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

        echo '<div class="wrap">';

        switch ($action) {
            case 'new':
            case 'edit':
                self::renderForm();
                break;
            default:
                self::renderList();
                break;
        }

        echo '</div>';
    }

    /**
     * Traiter les actions (creation, modification, suppression)
     * Appele via admin_init pour rediriger AVANT l'output WordPress
     */
    public static function handleActions(): void {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !(isset($_GET['action']) && $_GET['action'] === 'delete')) {
            return;
        }

        if (!isset($_POST['_wpnonce'])) {
            return;
        }

        $nonce = sanitize_text_field(wp_unslash($_POST['_wpnonce']));

        // Sauvegarde d'un client
        if (wp_verify_nonce($nonce, 'cfp_save_client')) {
            $data = [
                'name' => sanitize_text_field(wp_unslash($_POST['name'] ?? '')),
                'email' => sanitize_email(wp_unslash($_POST['email'] ?? '')),
                'address' => sanitize_text_field(wp_unslash($_POST['address'] ?? '')),
                'postal_code' => sanitize_text_field(wp_unslash($_POST['postal_code'] ?? '')),
                'city' => sanitize_text_field(wp_unslash($_POST['city'] ?? '')),
                'country' => sanitize_text_field(wp_unslash($_POST['country'] ?? 'France')),
                'siret' => sanitize_text_field(wp_unslash($_POST['siret'] ?? '')),
                'vat_number' => sanitize_text_field(wp_unslash($_POST['vat_number'] ?? '')),
                'phone' => sanitize_text_field(wp_unslash($_POST['phone'] ?? '')),
                'notes' => sanitize_textarea_field(wp_unslash($_POST['notes'] ?? '')),
            ];

            $client_id = isset($_POST['client_id']) ? absint($_POST['client_id']) : 0;

            if ($client_id > 0) {
                $result = ClientService::update($client_id, $data);
                if ($result) {
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-clients&message=updated'));
                    exit;
                }
            } else {
                $result = ClientService::create($data);
                if ($result) {
                    wp_safe_redirect(admin_url('admin.php?page=comptaflow-clients&message=created'));
                    exit;
                }
            }
        }

        // Suppression d'un client
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
            $delete_nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            $delete_id = absint($_GET['id']);

            if (wp_verify_nonce($delete_nonce, 'cfp_delete_client_' . $delete_id)) {
                $result = ClientService::delete($delete_id);
                $msg = ($result === true) ? 'deleted' : 'error_delete';
                wp_safe_redirect(admin_url('admin.php?page=comptaflow-clients&message=' . $msg));
                exit;
            }
        }
    }

    /**
     * Afficher la liste des clients
     */
    private static function renderList(): void {
        $clients = ClientService::getAll();
        $message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';

        echo '<h1>';
        echo esc_html__('Clients', 'comptaflow-by-meetempo');
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-clients&action=new')) . '" class="page-title-action">' . esc_html__('Add Client', 'comptaflow-by-meetempo') . '</a>';
        echo '</h1>';

        if ($message === 'created') {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Client created successfully.', 'comptaflow-by-meetempo') . '</p></div>';
        } elseif ($message === 'updated') {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Client updated.', 'comptaflow-by-meetempo') . '</p></div>';
        } elseif ($message === 'deleted') {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Client deleted.', 'comptaflow-by-meetempo') . '</p></div>';
        } elseif ($message === 'error_delete') {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__('Cannot delete this client (linked invoices).', 'comptaflow-by-meetempo') . '</p></div>';
        }

        if (empty($clients)) {
            echo '<div class="notice notice-info"><p>' . esc_html__('No clients registered.', 'comptaflow-by-meetempo') . ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-clients&action=new')) . '">' . esc_html__('Create your first client', 'comptaflow-by-meetempo') . '</a></p></div>';
            return;
        }

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

        foreach ($clients as $client) {
            $edit_url = admin_url('admin.php?page=comptaflow-clients&action=edit&id=' . absint($client['id']));
            $delete_url = wp_nonce_url(
                admin_url('admin.php?page=comptaflow-clients&action=delete&id=' . absint($client['id'])),
                'cfp_delete_client_' . absint($client['id'])
            );

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

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

    /**
     * Afficher le formulaire de creation/modification
     */
    private static function renderForm(): void {
        $client_id = isset($_GET['id']) ? absint($_GET['id']) : 0;
        $client = $client_id ? ClientService::getById($client_id) : null;
        $is_edit = !empty($client);

        echo '<h1>' . esc_html($is_edit ? __('Edit Client', 'comptaflow-by-meetempo') : __('New Client', 'comptaflow-by-meetempo')) . '</h1>';

        echo '<form method="post" action="' . esc_url(admin_url('admin.php?page=comptaflow-clients')) . '">';
        wp_nonce_field('cfp_save_client');

        if ($is_edit) {
            echo '<input type="hidden" name="client_id" value="' . esc_attr($client_id) . '">';
        }

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

        // Name
        echo '<tr><th><label for="name">' . esc_html__('Name / Company *', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="name" id="name" class="regular-text" required value="' . esc_attr($client['name'] ?? '') . '"></td></tr>';

        // Email
        echo '<tr><th><label for="email">' . esc_html__('Email *', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="email" name="email" id="email" class="regular-text" required value="' . esc_attr($client['email'] ?? '') . '"></td></tr>';

        // Phone
        echo '<tr><th><label for="phone">' . esc_html__('Phone', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="phone" id="phone" class="regular-text" value="' . esc_attr($client['phone'] ?? '') . '"></td></tr>';

        // Address
        echo '<tr><th><label for="address">' . esc_html__('Address', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="address" id="address" class="large-text" value="' . esc_attr($client['address'] ?? '') . '"></td></tr>';

        // Postal Code + City
        echo '<tr><th><label for="postal_code">' . esc_html__('Postal Code', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="postal_code" id="postal_code" style="width:100px;" value="' . esc_attr($client['postal_code'] ?? '') . '">';
        echo ' <input type="text" name="city" id="city" placeholder="' . esc_attr__('City', 'comptaflow-by-meetempo') . '" style="width:200px;" value="' . esc_attr($client['city'] ?? '') . '"></td></tr>';

        // Country
        echo '<tr><th><label for="country">' . esc_html__('Country', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="country" id="country" class="regular-text" value="' . esc_attr($client['country'] ?? 'France') . '"></td></tr>';

        // SIRET
        echo '<tr><th><label for="siret">' . esc_html__('SIRET', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="siret" id="siret" class="regular-text" value="' . esc_attr($client['siret'] ?? '') . '"></td></tr>';

        // VAT Number
        echo '<tr><th><label for="vat_number">' . esc_html__('Intra-community VAT Number', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" name="vat_number" id="vat_number" class="regular-text" value="' . esc_attr($client['vat_number'] ?? '') . '"></td></tr>';

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

        echo '</table>';

        echo '<p class="submit">';
        echo '<input type="submit" class="button button-primary" value="' . esc_attr($is_edit ? __('Update', 'comptaflow-by-meetempo') : __('Create Client', 'comptaflow-by-meetempo')) . '">';
        echo ' <a href="' . esc_url(admin_url('admin.php?page=comptaflow-clients')) . '" class="button">' . esc_html__('Cancel', 'comptaflow-by-meetempo') . '</a>';
        echo '</p>';

        echo '</form>';

        // Statistiques si modification
        if ($is_edit) {
            $stats = ClientService::getStats($client_id);
            echo '<div class="cfp-postbox">';
            echo '<h3>' . esc_html__('Statistics', 'comptaflow-by-meetempo') . '</h3>';
            echo '<p><strong>' . esc_html($stats['invoices_count']) . '</strong> ' . esc_html__('invoice(s)', 'comptaflow-by-meetempo') . ' — ';
            echo esc_html__('Total', 'comptaflow-by-meetempo') . ' : <strong>' . esc_html(number_format($stats['invoices_total'], 2, ',', ' ')) . ' &euro;</strong> — ';
            echo esc_html__('Unpaid', 'comptaflow-by-meetempo') . ' : <strong style="color: #d63638;">' . esc_html(number_format($stats['invoices_unpaid'], 2, ',', ' ')) . ' &euro;</strong></p>';
            echo '</div>';
        }
    }
}
