<?php
if (!defined('ABSPATH')) {
    exit;
}

class Manfiet_Client_Manager {
    public const POST_TYPE = 'manfiet_client';
    private const REST_NAMESPACE = 'manfi-expense-tracker/v1';

    public function __construct() {
        add_action('init', [$this, 'register_post_type']);
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public static function install() {
        self::register_post_type_static();
        flush_rewrite_rules();
    }

    public function register_post_type() {
        self::register_post_type_static();
    }

    public static function register_post_type_static() {
        register_post_type(self::POST_TYPE, [
            'labels' => [
                'name' => __('Clients', 'manfi-expense-tracker'),
                'singular_name' => __('Client', 'manfi-expense-tracker'),
            ],
            'public' => false,
            'show_ui' => false,
            'show_in_menu' => false,
            'show_in_rest' => false,
            'supports' => ['title'],
            'has_archive' => false,
            'rewrite' => false,
        ]);
    }

    private function can_manage_clients() {
        return current_user_can('manage_expenses') || current_user_can('manage_options');
    }

    public function require_manage_permission() {
        if (!$this->can_manage_clients()) {
            return new WP_Error(
                'manfiet_client_forbidden',
                __('You do not have permission to manage clients.', 'manfi-expense-tracker'),
                ['status' => 403]
            );
        }

        return true;
    }

    private function get_client_payload($client_id) {
        $post = get_post($client_id);
        if (!$post || $post->post_type !== self::POST_TYPE) {
            return null;
        }

        $raw_phones = get_post_meta($client_id, '_manfiet_client_phones', true);
        $phones = json_decode((string) $raw_phones, true);
        if (!is_array($phones) || empty($phones)) {
            $single_phone = (string) get_post_meta($client_id, '_manfiet_client_phone', true);
            $phones = $single_phone !== '' ? [$single_phone] : [];
        }

        $raw_emails = get_post_meta($client_id, '_manfiet_client_emails', true);
        $emails = json_decode((string) $raw_emails, true);
        if (!is_array($emails) || empty($emails)) {
            $e1 = (string) get_post_meta($client_id, '_manfiet_client_email', true);
            $e2 = (string) get_post_meta($client_id, '_manfiet_client_email2', true);
            $emails = array_values(array_filter([$e1, $e2]));
        }

        return [
            'id' => $post->ID,
            'title' => get_the_title($post),
            'client_name' => (string) get_post_meta($client_id, '_manfiet_client_name', true),
            'contact_person' => (string) get_post_meta($client_id, '_manfiet_client_contact_person', true),
            'phone' => $phones[0] ?? (string) get_post_meta($client_id, '_manfiet_client_phone', true),
            'phones' => array_values(array_filter(array_map('sanitize_text_field', $phones))),
            'email' => $emails[0] ?? (string) get_post_meta($client_id, '_manfiet_client_email', true),
            'email2' => $emails[1] ?? (string) get_post_meta($client_id, '_manfiet_client_email2', true),
            'emails' => array_values(array_filter(array_map('sanitize_email', $emails))),
            'address' => (string) get_post_meta($client_id, '_manfiet_client_address', true),
        ];
    }

    private function save_client_meta($client_id, array $payload) {
        $contact_person = sanitize_text_field((string) ($payload['contact_person'] ?? ''));

        // Handle phones array & single fallback
        $raw_phones = $payload['phones'] ?? [];
        if (!is_array($raw_phones)) {
            $raw_phones = !empty($payload['phone']) ? [$payload['phone']] : [];
        }
        $phones = array_values(array_filter(array_map('sanitize_text_field', (array) $raw_phones)));

        // Handle emails array & single fallback
        $raw_emails = $payload['emails'] ?? [];
        if (!is_array($raw_emails)) {
            $raw_emails = array_filter([$payload['email'] ?? '', $payload['email2'] ?? '']);
        }
        $emails = array_values(array_filter(array_map('sanitize_email', (array) $raw_emails)));

        $fields = [
            '_manfiet_client_name' => sanitize_text_field((string) ($payload['client_name'] ?? '')),
            '_manfiet_client_contact_person' => $contact_person,
            '_manfiet_client_phone' => $phones[0] ?? sanitize_text_field((string) ($payload['phone'] ?? '')),
            '_manfiet_client_phones' => wp_json_encode($phones),
            '_manfiet_client_email' => $emails[0] ?? sanitize_email((string) ($payload['email'] ?? '')),
            '_manfiet_client_email2' => $emails[1] ?? sanitize_email((string) ($payload['email2'] ?? '')),
            '_manfiet_client_emails' => wp_json_encode($emails),
            '_manfiet_client_address' => sanitize_textarea_field((string) ($payload['address'] ?? '')),
        ];

        foreach ($fields as $meta_key => $value) {
            update_post_meta($client_id, $meta_key, $value);
        }
    }

    public function register_routes() {
        register_rest_route(self::REST_NAMESPACE, '/clients', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'rest_list_clients'],
                'permission_callback' => [$this, 'require_manage_permission'],
            ],
            [
                'methods' => 'POST',
                'callback' => [$this, 'rest_create_client'],
                'permission_callback' => [$this, 'require_manage_permission'],
            ],
        ]);

        register_rest_route(self::REST_NAMESPACE, '/clients/(?P<id>\d+)', [
            [
                'methods' => 'GET',
                'callback' => [$this, 'rest_get_client'],
                'permission_callback' => [$this, 'require_manage_permission'],
            ],
            [
                'methods' => 'PUT,PATCH',
                'callback' => [$this, 'rest_update_client'],
                'permission_callback' => [$this, 'require_manage_permission'],
            ],
            [
                'methods' => 'DELETE',
                'callback' => [$this, 'rest_delete_client'],
                'permission_callback' => [$this, 'require_manage_permission'],
            ],
        ]);
    }

    public function rest_list_clients() {
        $posts = get_posts([
            'post_type' => self::POST_TYPE,
            'post_status' => ['publish', 'draft', 'private'],
            'numberposts' => -1,
            'orderby' => 'date',
            'order' => 'DESC',
        ]);

        $items = [];
        foreach ($posts as $post) {
            $payload = $this->get_client_payload($post->ID);
            if ($payload) {
                $items[] = $payload;
            }
        }

        return rest_ensure_response($items);
    }

    public function rest_get_client(WP_REST_Request $request) {
        $client_id = absint($request['id']);
        $payload = $this->get_client_payload($client_id);
        if (!$payload) {
            return new WP_Error('manfiet_client_not_found', __('Client not found.', 'manfi-expense-tracker'), ['status' => 404]);
        }

        return rest_ensure_response($payload);
    }

    public function rest_create_client(WP_REST_Request $request) {
        $data = $request->get_json_params();
        $client_name = sanitize_text_field((string) ($data['client_name'] ?? ''));

        if ($client_name === '') {
            return new WP_Error('manfiet_client_required', __('Client name is required.', 'manfi-expense-tracker'), ['status' => 400]);
        }

        $post_id = wp_insert_post([
            'post_type' => self::POST_TYPE,
            'post_status' => 'publish',
            'post_title' => $client_name,
            'post_content' => '',
            'post_author' => get_current_user_id(),
        ], true);

        if (is_wp_error($post_id) || !$post_id) {
            return new WP_Error('manfiet_client_insert_failed', __('Could not insert client.', 'manfi-expense-tracker'), ['status' => 500]);
        }

        $this->save_client_meta($post_id, [
            'client_name' => $client_name,
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'] ?? '',
            'email2' => $data['email2'] ?? '',
            'address' => $data['address'] ?? '',
        ]);

        return rest_ensure_response($this->get_client_payload($post_id));
    }

    public function rest_update_client(WP_REST_Request $request) {
        $client_id = absint($request['id']);
        if (!$this->get_client_payload($client_id)) {
            return new WP_Error('manfiet_client_not_found', __('Client not found.', 'manfi-expense-tracker'), ['status' => 404]);
        }

        $data = $request->get_json_params();
        $client_name = sanitize_text_field((string) ($data['client_name'] ?? ''));

        if ($client_name === '') {
            return new WP_Error('manfiet_client_required', __('Client name is required.', 'manfi-expense-tracker'), ['status' => 400]);
        }

        wp_update_post([
            'ID' => $client_id,
            'post_title' => $client_name,
        ]);

        $this->save_client_meta($client_id, [
            'client_name' => $client_name,
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'] ?? '',
            'email2' => $data['email2'] ?? '',
            'address' => $data['address'] ?? '',
        ]);

        return rest_ensure_response($this->get_client_payload($client_id));
    }

    public function rest_delete_client(WP_REST_Request $request) {
        $client_id = absint($request['id']);
        $result = wp_trash_post($client_id);
        if (!$result) {
            return new WP_Error('manfiet_client_delete_failed', __('Failed to delete client.', 'manfi-expense-tracker'), ['status' => 400]);
        }

        return rest_ensure_response(['deleted' => true]);
    }
}
