<?php

    namespace App\Livewire\Tickets;

    use App\Http\Controllers\{TicketsController};
    use App\Models\{User,Departments,Tickets,Attachment};
    use App\Services\AttachmentService;
    use Illuminate\Support\Facades\Auth;
    use Livewire\Attributes\{Rule, Validate};
    use Livewire\Component;
    use Livewire\WithFileUploads;
    use Filament\Notifications\Notification;

    class Create extends Component
    {
        use WithFileUploads;

        public $department_id;
        public $department;

        public $customer_id;

        #[Rule(message: "Please enter your full name, so we can personalize our reply.")]
        public $public_name = '';

        #[Rule(message: "Please enter your email address, so you get our reply.")]
        public $public_email = '';

        #[Rule('required', message: "Please enter a subject.")]
        #[Validate('required')]
        public $subject;

        public $cc;

        public $priority = 'low';

        #[Rule('required', message: "Please enter the reason you are contacting us?")]
        #[Validate('required')]
        public $content;

        public $files = [];
        public $settings = [];

        public function mount($department_id, $department)
        {
            $this->department_id = $department_id;
            $this->department    = $department;

            // Load attachment settings for this department
            $this->settings = AttachmentService::getSettingsForDepartment($department_id);
            // No existing attachments when creating a new ticket
            $this->settings['current_file_count'] = 0;
        }

        public function updatedFiles()
        {
            // Validate files on upload
            $this->validate([
                'files.*' => [
                    'file',
                    'max:' . ($this->settings['max_file_size_mb'] * 1024), // Convert MB to KB for validation
                ],
            ], [
                'files.*.max' => 'File size must not exceed ' . $this->settings['max_file_size_mb'] . 'MB.',
            ]);
        }

        public function save()
        {
            $this->validate();

            $token = bin2hex(random_bytes(16));
            $public_hash = hash_hmac('sha256', $token, config('app.key'));

            // If no customer selected or invalid value, use the authenticated employee's ID
            $customerId = (!empty($this->customer_id) && is_numeric($this->customer_id))
                ? $this->customer_id
                : Auth::user()->id;

            $ticket_id = TicketsController::store([
                'customer_id' => $customerId,
                'public_name' => $this->public_name,
                'public_email' => $this->public_email,
                'subject' => $this->subject,
                'cc' => $this->cc,
                'priority' => $this->priority ?: 'none',
                'message' => $this->content,
                'department_id' => $this->department_id,
                'public_hash' => $public_hash,
                'organize' => 'ticket',
            ]);

            // Upload files if any were selected and attachments are enabled
            if (!empty($this->files) && $this->settings['enabled']) {
                $uploadedCount = 0;
                $errors = [];

                // Get user_id for the attachment
                $userId = $this->customer_id ?? Auth::id() ?? 0;

                // Get ticket to access user_id if not authenticated
                if ($userId === 0) {
                    $ticket = Tickets::find($ticket_id);
                    $userId = $ticket->user_id ?? 0;
                }

                foreach ($this->files as $file) {
                    try {
                        AttachmentService::upload(
                            $file,
                            $ticket_id,
                            $userId,
                            null, // No response_id for ticket-level attachments
                            false
                        );
                        $uploadedCount++;
                    } catch (\Exception $e) {
                        $errors[] = $file->getClientOriginalName() . ': ' . $e->getMessage();
                    }
                }

                if (!empty($errors)) {
                    Notification::make()
                        ->title('Some files failed to upload')
                        ->warning()
                        ->body(implode("\n", $errors))
                        ->send();
                }
            }

            // Dispatch event to update sidebar counts
            $this->dispatch('ticket-updated')->to('sidebar-navigation');
            $this->dispatch('ticket-updated')->to('sidebar-assigned-tickets');

            Notification::make()
                    ->title('Ticket created successfully')
                    ->success()
                    ->body('Your ticket has been created successfully, our team will look into it shortly.')
                    ->color('success') 
                    ->send();
            /*
            *
            * Need to fix this to try and show notifications for agents.
            *

            $recipients = User::where('is_agent', '=', '1')->get();
            foreach( $recipients as $recipient){
                    Notification::make()
                        ->title('New ticket has been opened.')
                        ->success()
                        ->body('A ticket has been opened.')
                        ->color('success')
                        ->broadcast($recipient);
            }
            
            */

            if (Auth::check()) {
                $this->redirect('/tickets/show/'.$ticket_id);
            } else {
                $public_ticket = Tickets::where('id', '=', $ticket_id)->first();
                $this->redirect('/tickets/public/'.$public_ticket->id.'/'.$public_ticket->public_hash);
            }
            $this->reset();

        }

        public function getAcceptedFileTypes()
        {
            $allowed = $this->settings['allowed_file_types'] ?? [];

            if (empty($allowed)) {
                return '*';
            }

            // Convert extensions to accept attribute format
            $extensions = array_filter($allowed, fn($type) => !str_contains($type, '/'));

            return !empty($extensions) ? '.' . implode(',.', $extensions) : '*';
        }

        public function render()
        {
            $users = User::select('id', 'name', 'email')->get();
            return view('livewire.tickets.create', [
                'department_info' => $this->department,
                'ip_address' => app('request')->ip(),
                'users' => $users,
            ]);
        }
    }
