<?php

namespace Modules\CRMCore\App\Settings;

use App\Services\Settings\BaseModuleSettings;

class CRMCoreSettings extends BaseModuleSettings
{
    protected string $module = 'CRMCore';

    /**
     * Define module settings
     * Keys must match CRMCoreSettingsHandler and service usages
     */
    protected function define(): array
    {
        return [
            'companies' => [
                'auto_generate_company_codes' => [
                    'label' => __('Auto Generate Company Codes'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for new companies'),
                ],
                'company_code_prefix' => [
                    'label' => __('Company Code Prefix'),
                    'type' => 'text',
                    'default' => 'COM',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for auto-generated company codes (e.g., COM-001)'),
                ],
                'company_code_start_number' => [
                    'label' => __('Starting Company Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for company code sequence'),
                ],
                'enable_company_industry_categories' => [
                    'label' => __('Enable Industry Categories'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Allow categorizing companies by industry'),
                ],
                'require_company_assignment' => [
                    'label' => __('Require Company Assignment'),
                    'type' => 'switch',
                    'default' => false,
                    'validation' => 'boolean',
                    'help' => __('Make user assignment mandatory for companies'),
                ],
                'default_company_industry' => [
                    'label' => __('Default Industry'),
                    'type' => 'text',
                    'default' => '',
                    'validation' => 'nullable|string|max:100',
                    'help' => __('Default industry for new companies'),
                ],
            ],
            'contacts' => [
                'auto_generate_contact_codes' => [
                    'label' => __('Auto Generate Contact Codes'),
                    'type' => 'switch',
                    'default' => false,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for contacts'),
                ],
                'contact_code_prefix' => [
                    'label' => __('Contact Code Prefix'),
                    'type' => 'text',
                    'default' => 'CNT',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for contact codes (e.g., CNT-001)'),
                ],
                'contact_code_start_number' => [
                    'label' => __('Starting Contact Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for contact code sequence'),
                ],
                'enable_contact_duplicate_detection' => [
                    'label' => __('Enable Duplicate Detection'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Check for duplicate contacts by email and phone'),
                ],
                'duplicate_detection_fields' => [
                    'label' => __('Duplicate Detection Fields'),
                    'type' => 'select',
                    'default' => 'email_and_phone',
                    'validation' => 'required|in:email,phone,email_and_phone,email_or_phone',
                    'options' => [
                        'email' => __('Email Only'),
                        'phone' => __('Phone Only'),
                        'email_and_phone' => __('Email AND Phone'),
                        'email_or_phone' => __('Email OR Phone'),
                    ],
                    'help' => __('Fields to check for duplicates'),
                ],
                'require_company_for_contacts' => [
                    'label' => __('Require Company for Contacts'),
                    'type' => 'switch',
                    'default' => false,
                    'validation' => 'boolean',
                    'help' => __('Make company field mandatory when creating contacts'),
                ],
                'require_contact_assignment' => [
                    'label' => __('Require Contact Assignment'),
                    'type' => 'switch',
                    'default' => false,
                    'validation' => 'boolean',
                    'help' => __('Make user assignment mandatory for contacts'),
                ],
            ],
            'customers' => [
                'auto_generate_customer_codes' => [
                    'label' => __('Auto Generate Customer Codes'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for new customers'),
                ],
                'customer_code_prefix' => [
                    'label' => __('Customer Code Prefix'),
                    'type' => 'text',
                    'default' => 'CUS',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for auto-generated customer codes (e.g., CUS-001)'),
                ],
                'customer_code_start_number' => [
                    'label' => __('Starting Customer Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for customer code sequence'),
                ],
                'auto_create_customer_on_first_purchase' => [
                    'label' => __('Auto Create Customer on First Purchase'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Automatically create customer record on first purchase'),
                ],
                'default_credit_limit' => [
                    'label' => __('Default Credit Limit'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'nullable|numeric|min:0',
                    'attributes' => ['min' => '0'],
                    'help' => __('Default credit limit for new customers'),
                ],
                'default_payment_terms' => [
                    'label' => __('Default Payment Terms'),
                    'type' => 'select',
                    'default' => 'cod',
                    'validation' => 'required|in:cod,net15,net30,net60,net90,prepaid',
                    'options' => [
                        'cod' => __('Cash on Delivery'),
                        'net15' => __('Net 15 Days'),
                        'net30' => __('Net 30 Days'),
                        'net60' => __('Net 60 Days'),
                        'net90' => __('Net 90 Days'),
                        'prepaid' => __('Prepaid'),
                    ],
                    'help' => __('Default payment terms for new customers'),
                ],
                'enable_customer_duplicate_detection' => [
                    'label' => __('Enable Customer Duplicate Detection'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Check for duplicate customers when creating'),
                ],
            ],
            'leads' => [
                'auto_generate_lead_codes' => [
                    'label' => __('Auto Generate Lead Codes'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for new leads'),
                ],
                'lead_code_prefix' => [
                    'label' => __('Lead Code Prefix'),
                    'type' => 'text',
                    'default' => 'LD',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for auto-generated lead codes (e.g., LD-001)'),
                ],
                'lead_code_start_number' => [
                    'label' => __('Starting Lead Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for lead code sequence'),
                ],
                'require_lead_assignment' => [
                    'label' => __('Require Lead Assignment'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Require all leads to be assigned to a user'),
                ],
                'lead_auto_convert_days' => [
                    'label' => __('Auto Convert Qualified Leads (Days)'),
                    'type' => 'number',
                    'default' => '30',
                    'validation' => 'nullable|integer|min:0',
                    'attributes' => ['min' => '0'],
                    'help' => __('Automatically convert qualified leads after X days (0 to disable)'),
                ],
            ],
            'deals' => [
                'auto_generate_deal_codes' => [
                    'label' => __('Auto Generate Deal Codes'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for new deals'),
                ],
                'deal_code_prefix' => [
                    'label' => __('Deal Code Prefix'),
                    'type' => 'text',
                    'default' => 'DL',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for auto-generated deal codes (e.g., DL-001)'),
                ],
                'deal_code_start_number' => [
                    'label' => __('Starting Deal Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for deal code sequence'),
                ],
                'require_deal_assignment' => [
                    'label' => __('Require Deal Assignment'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Require all deals to be assigned to a user'),
                ],
                'default_deal_probability' => [
                    'label' => __('Default Deal Probability (%)'),
                    'type' => 'number',
                    'default' => '10',
                    'validation' => 'required|integer|min:0|max:100',
                    'attributes' => ['min' => '0', 'max' => '100'],
                    'help' => __('Default probability percentage for new deals'),
                ],
                'deal_auto_close_days' => [
                    'label' => __('Auto Close Stale Deals (Days)'),
                    'type' => 'number',
                    'default' => '90',
                    'validation' => 'nullable|integer|min:0',
                    'attributes' => ['min' => '0'],
                    'help' => __('Automatically close deals with no activity after X days (0 to disable)'),
                ],
            ],
            'tasks' => [
                'auto_generate_task_codes' => [
                    'label' => __('Auto Generate Task Codes'),
                    'type' => 'switch',
                    'default' => false,
                    'validation' => 'boolean',
                    'help' => __('Automatically generate unique codes for new tasks'),
                ],
                'task_code_prefix' => [
                    'label' => __('Task Code Prefix'),
                    'type' => 'text',
                    'default' => 'TSK',
                    'validation' => 'nullable|string|max:10',
                    'help' => __('Prefix for auto-generated task codes (e.g., TSK-001)'),
                ],
                'task_code_start_number' => [
                    'label' => __('Starting Task Number'),
                    'type' => 'number',
                    'default' => '1000',
                    'validation' => 'required|integer|min:1',
                    'attributes' => ['min' => '1'],
                    'help' => __('Starting number for task code sequence'),
                ],
                'require_task_assignment' => [
                    'label' => __('Require Task Assignment'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Require all tasks to be assigned to a user'),
                ],
                'task_reminder_enabled' => [
                    'label' => __('Enable Task Reminders'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Send reminder notifications for upcoming tasks'),
                ],
                'task_reminder_before_hours' => [
                    'label' => __('Task Reminder Hours'),
                    'type' => 'number',
                    'default' => '24',
                    'validation' => 'required|integer|min:1|max:168',
                    'attributes' => ['min' => '1', 'max' => '168'],
                    'help' => __('Hours before due date to send reminders (max 7 days)'),
                ],
                'enable_task_time_tracking' => [
                    'label' => __('Enable Time Tracking'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Track estimated and actual hours for tasks'),
                ],
            ],
            'notifications' => [
                'notify_lead_assignment' => [
                    'label' => __('Notify on Lead Assignment'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Send notification when leads are assigned'),
                ],
                'notify_deal_stage_change' => [
                    'label' => __('Notify on Deal Stage Change'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Send notification when deal stages change'),
                ],
                'notify_task_due' => [
                    'label' => __('Notify on Task Due'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Send notification when tasks are due'),
                ],
            ],
            'display' => [
                'items_per_page' => [
                    'label' => __('Items Per Page'),
                    'type' => 'select',
                    'default' => '25',
                    'validation' => 'required|in:10,25,50,100',
                    'options' => [
                        '10' => '10',
                        '25' => '25',
                        '50' => '50',
                        '100' => '100',
                    ],
                    'help' => __('Default number of items per page in listings'),
                ],
                'enable_kanban_view' => [
                    'label' => __('Enable Kanban View'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Enable kanban board view for deals and tasks'),
                ],
                'show_activity_timeline' => [
                    'label' => __('Show Activity Timeline'),
                    'type' => 'switch',
                    'default' => true,
                    'validation' => 'boolean',
                    'help' => __('Show activity timeline in entity detail views'),
                ],
            ],
        ];
    }

    /**
     * Get module display name
     */
    public function getModuleName(): string
    {
        return __('CRM Settings');
    }

    /**
     * Get module description
     */
    public function getModuleDescription(): string
    {
        return __('Configure customer relationship management settings for leads, deals, tasks, and more');
    }

    /**
     * Get module icon
     */
    public function getModuleIcon(): string
    {
        return 'bx bx-user-check';
    }

    /**
     * Convert settings format to fields format for view
     */
    private function convertFieldsFormat(array $settings): array
    {
        $fields = [];
        foreach ($settings as $name => $field) {
            $fieldData = [
                'name' => $name,
                'label' => $field['label'],
                'type' => $field['type'],
                'default' => $field['default'],
                'help' => $field['help'] ?? null,
            ];

            // Check if field is required
            $validationRules = explode('|', $field['validation'] ?? '');
            $fieldData['required'] = in_array('required', $validationRules);

            // Add type-specific attributes
            if ($field['type'] === 'number' && isset($field['attributes'])) {
                $fieldData['min'] = $field['attributes']['min'] ?? null;
                $fieldData['max'] = $field['attributes']['max'] ?? null;
                $fieldData['step'] = $field['attributes']['step'] ?? null;
            }

            if ($field['type'] === 'select') {
                $fieldData['options'] = $field['options'] ?? [];
                $fieldData['options_source'] = $field['options_source'] ?? null;
            }

            $fields[] = $fieldData;
        }

        return $fields;
    }

    /**
     * Get settings sections
     */
    public function getSections(): array
    {
        $settings = $this->define();

        return [
            [
                'id' => 'companies',
                'title' => __('Company Settings'),
                'icon' => 'bx bx-buildings',
                'description' => __('Configure company code generation and assignment rules'),
                'fields' => $this->convertFieldsFormat($settings['companies']),
            ],
            [
                'id' => 'contacts',
                'title' => __('Contact Settings'),
                'icon' => 'bx bx-user',
                'description' => __('Configure contact duplicate detection and requirements'),
                'fields' => $this->convertFieldsFormat($settings['contacts']),
            ],
            [
                'id' => 'customers',
                'title' => __('Customer Settings'),
                'icon' => 'bx bx-group',
                'description' => __('Configure customer code generation and defaults'),
                'fields' => $this->convertFieldsFormat($settings['customers']),
            ],
            [
                'id' => 'leads',
                'title' => __('Lead Settings'),
                'icon' => 'bx bx-user-plus',
                'description' => __('Configure lead code generation and assignment rules'),
                'fields' => $this->convertFieldsFormat($settings['leads']),
            ],
            [
                'id' => 'deals',
                'title' => __('Deal Settings'),
                'icon' => 'bx bx-trophy',
                'description' => __('Configure deal code generation and defaults'),
                'fields' => $this->convertFieldsFormat($settings['deals']),
            ],
            [
                'id' => 'tasks',
                'title' => __('Task Settings'),
                'icon' => 'bx bx-task',
                'description' => __('Configure task code generation, assignment, and reminders'),
                'fields' => $this->convertFieldsFormat($settings['tasks']),
            ],
            [
                'id' => 'notifications',
                'title' => __('Notification Settings'),
                'icon' => 'bx bx-bell',
                'description' => __('Configure what events trigger notifications'),
                'fields' => $this->convertFieldsFormat($settings['notifications']),
            ],
            [
                'id' => 'display',
                'title' => __('Display Settings'),
                'icon' => 'bx bx-show',
                'description' => __('Configure display and view preferences'),
                'fields' => $this->convertFieldsFormat($settings['display']),
            ],
        ];
    }

    /**
     * Get validation rules
     */
    public function getValidationRules(): array
    {
        $rules = [];
        foreach ($this->define() as $section => $settings) {
            foreach ($settings as $key => $field) {
                if (isset($field['validation'])) {
                    $rules[$key] = $field['validation'];
                }
            }
        }

        return $rules;
    }

    /**
     * Get default values
     */
    public function getDefaults(): array
    {
        $defaults = [];
        foreach ($this->define() as $section => $settings) {
            foreach ($settings as $key => $field) {
                $defaults[$key] = $field['default'];
            }
        }

        return $defaults;
    }
}
