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

class Manfiet_Vendor_Manager {
    public const POST_TYPE = 'manfiet_vendor';
    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' => __('Vendors', 'manfi-expense-tracker'),
                'singular_name' => __('Vendor', '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_vendors() {
        return current_user_can('manage_expenses') || current_user_can('manage_options');
    }

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

        return true;
    }

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

        return [
            'id' => $post->ID,
            'title' => get_the_title($post),
            'company_name' => (string) get_post_meta($vendor_id, '_manfiet_vendor_company_name', true),
            'phone' => (string) get_post_meta($vendor_id, '_manfiet_vendor_phone', true),
            'email' => (string) get_post_meta($vendor_id, '_manfiet_vendor_email', true),
            'address' => (string) get_post_meta($vendor_id, '_manfiet_vendor_address', true),
            'logo_url' => (string) get_post_meta($vendor_id, '_manfiet_vendor_logo_url', true),
            'website_url' => (string) get_post_meta($vendor_id, '_manfiet_vendor_website_url', true),
            'tagline' => (string) get_post_meta($vendor_id, '_manfiet_vendor_tagline', true),
        ];
    }

    private function sanitize_multi_urls($input) {
        $raw_items = preg_split('/[\r\n,]+/', (string) $input);
        $clean = [];
        foreach ($raw_items as $item) {
            $url = esc_url_raw(trim($item));
            if ($url !== '') {
                $clean[] = $url;
            }
        }
        return implode(', ', $clean);
    }

    private function sanitize_multi_emails($input) {
        $raw_items = preg_split('/[\r\n,]+/', (string) $input);
        $clean = [];
        foreach ($raw_items as $item) {
            $email = sanitize_email(trim($item));
            if ($email !== '') {
                $clean[] = $email;
            }
        }
        return implode(', ', $clean);
    }

    private function save_vendor_meta($vendor_id, array $payload) {
        $fields = [
            '_manfiet_vendor_company_name' => sanitize_text_field((string) ($payload['company_name'] ?? '')),
            '_manfiet_vendor_phone' => sanitize_textarea_field((string) ($payload['phone'] ?? '')),
            '_manfiet_vendor_email' => $this->sanitize_multi_emails((string) ($payload['email'] ?? '')),
            '_manfiet_vendor_address' => sanitize_textarea_field((string) ($payload['address'] ?? '')),
            '_manfiet_vendor_logo_url' => $this->sanitize_multi_urls((string) ($payload['logo_url'] ?? '')),
            '_manfiet_vendor_website_url' => $this->sanitize_multi_urls((string) ($payload['website_url'] ?? '')),
            '_manfiet_vendor_tagline' => sanitize_text_field((string) ($payload['tagline'] ?? '')),
        ];

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

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

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

    public function rest_list_vendors() {
        $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_vendor_payload($post->ID);
            if ($payload) {
                $items[] = $payload;
            }
        }

        return rest_ensure_response($items);
    }

    public function rest_get_vendor(WP_REST_Request $request) {
        $vendor_id = absint($request['id']);
        $payload = $this->get_vendor_payload($vendor_id);
        if (!$payload) {
            return new WP_Error('manfiet_vendor_not_found', __('Vendor not found.', 'manfi-expense-tracker'), ['status' => 404]);
        }

        return rest_ensure_response($payload);
    }

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

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

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

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

        $this->save_vendor_meta($post_id, [
            'company_name' => $company_name,
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'] ?? '',
            'address' => $data['address'] ?? '',
            'logo_url' => $data['logo_url'] ?? '',
            'website_url' => $data['website_url'] ?? '',
            'tagline' => $data['tagline'] ?? '',
        ]);

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

    public function rest_update_vendor(WP_REST_Request $request) {
        $vendor_id = absint($request['id']);
        if (!$this->get_vendor_payload($vendor_id)) {
            return new WP_Error('manfiet_vendor_not_found', __('Vendor not found.', 'manfi-expense-tracker'), ['status' => 404]);
        }

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

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

        wp_update_post([
            'ID' => $vendor_id,
            'post_title' => $company_name,
        ]);

        $this->save_vendor_meta($vendor_id, [
            'company_name' => $company_name,
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'] ?? '',
            'address' => $data['address'] ?? '',
            'logo_url' => $data['logo_url'] ?? '',
            'website_url' => $data['website_url'] ?? '',
            'tagline' => $data['tagline'] ?? '',
        ]);

        return rest_ensure_response($this->get_vendor_payload($vendor_id));
    }

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

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