<?php

namespace App\Controllers\Admin;

use CodeIgniter\Controller;
use App\Models\UserModel;

class TicketController extends Controller
{
    protected $userModel;

    public function __construct()
    {
        $this->userModel = new UserModel();
        
        // Verificar autenticación
        if (!session()->get('isLoggedIn')) {
            return redirect()->to(base_url('login'))->send();
        }
    }

    public function index()
    {
        $role = session()->get('role');
        $userId = session()->get('user_id');
        
        // Cargar tickets desde archivo JSON
        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        // Filtrar tickets según el rol
        if ($role === 'advisor') {
            // Los asesores solo ven tickets asignados a ellos
            $tickets = array_filter($tickets, function($ticket) use ($userId) {
                return isset($ticket['assigned_to']) && $ticket['assigned_to'] == $userId;
            });
        }

        // Aplicar filtros de la URL
        $statusFilter = $this->request->getGet('status');
        $assignedToFilter = $this->request->getGet('assigned_to');

        if ($statusFilter) {
            $tickets = array_filter($tickets, function($ticket) use ($statusFilter) {
                return $ticket['status'] === $statusFilter;
            });
        }

        if ($assignedToFilter) {
            $tickets = array_filter($tickets, function($ticket) use ($assignedToFilter) {
                return isset($ticket['assigned_to']) && $ticket['assigned_to'] == $assignedToFilter;
            });
        }

        // Obtener lista de asesores para asignación (solo admin)
        $advisors = [];
        if ($role === 'admin') {
            $advisors = $this->userModel->where('role', 'advisor')->findAll();
        }

        return view('admin/tickets/index', [
            'title' => 'Gestión de Tickets - Chat Solibot',
            'tickets' => $tickets,
            'advisors' => $advisors,
            'role' => $role,
            'userId' => $userId
        ]);
    }

    public function create()
    {
        // Solo admin puede crear tickets manualmente
        if (session()->get('role') !== 'admin') {
            return redirect()->to(base_url('admin/tickets'))->with('error', 'No autorizado');
        }

        $advisors = $this->userModel->where('role', 'advisor')->findAll();

        return view('admin/tickets/create', [
            'title' => 'Crear Ticket - Chat Solibot',
            'advisors' => $advisors
        ]);
    }

    public function store()
    {
        // Solo admin puede crear tickets manualmente
        if (session()->get('role') !== 'admin') {
            return redirect()->to(base_url('admin/tickets'))->with('error', 'No autorizado');
        }

        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        $newTicket = [
            'id' => uniqid(),
            'ticket_number' => $this->generateTicketNumber(),
            'platform' => $this->request->getPost('platform'),
            'user_platform_id' => $this->request->getPost('user_platform_id'),
            'user_name' => $this->request->getPost('user_name'),
            'user_phone' => $this->request->getPost('user_phone'),
            'subject' => $this->request->getPost('subject'),
            'description' => $this->request->getPost('description'),
            'status' => 'open',
            'priority' => $this->request->getPost('priority'),
            'assigned_to' => $this->request->getPost('assigned_to') ?: null,
            'category' => $this->request->getPost('category'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'assigned_at' => $this->request->getPost('assigned_to') ? date('Y-m-d H:i:s') : null
        ];

        $tickets[] = $newTicket;
        file_put_contents($ticketsFile, json_encode($tickets, JSON_PRETTY_PRINT));

        return redirect()->to(base_url('admin/tickets'))->with('success', 'Ticket creado exitosamente');
    }

    public function view($id)
    {
        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        $ticket = null;
        foreach ($tickets as $t) {
            if ($t['id'] === $id) {
                $ticket = $t;
                break;
            }
        }

        if (!$ticket) {
            return redirect()->to(base_url('admin/tickets'))->with('error', 'Ticket no encontrado');
        }

        // Verificar permisos para asesores
        $role = session()->get('role');
        $userId = session()->get('user_id');
        
        if ($role === 'advisor' && (!isset($ticket['assigned_to']) || $ticket['assigned_to'] != $userId)) {
            return redirect()->to(base_url('admin/tickets'))->with('error', 'No autorizado');
        }

        // Obtener información del asesor asignado
        $assignedAdvisor = null;
        if (isset($ticket['assigned_to']) && $ticket['assigned_to']) {
            $assignedAdvisor = $this->userModel->find($ticket['assigned_to']);
        }

        // Obtener lista de asesores para reasignación (solo admin)
        $advisors = [];
        if ($role === 'admin') {
            $advisors = $this->userModel->where('role', 'advisor')->findAll();
        }

        return view('admin/tickets/view', [
            'title' => 'Ticket #' . $ticket['ticket_number'] . ' - Chat Solibot',
            'ticket' => $ticket,
            'assignedAdvisor' => $assignedAdvisor,
            'advisors' => $advisors,
            'role' => $role
        ]);
    }

    public function update($id)
    {
        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        $role = session()->get('role');
        $userId = session()->get('user_id');

        foreach ($tickets as &$ticket) {
            if ($ticket['id'] === $id) {
                // Verificar permisos para asesores
                if ($role === 'advisor' && (!isset($ticket['assigned_to']) || $ticket['assigned_to'] != $userId)) {
                    return redirect()->to(base_url('admin/tickets'))->with('error', 'No autorizado');
                }

                // Actualizar campos según el rol
                if ($role === 'admin') {
                    // Admin puede actualizar todo
                    $ticket['subject'] = $this->request->getPost('subject');
                    $ticket['description'] = $this->request->getPost('description');
                    $ticket['status'] = $this->request->getPost('status');
                    $ticket['priority'] = $this->request->getPost('priority');
                    $ticket['category'] = $this->request->getPost('category');
                    
                    // Manejar asignación
                    $newAssignedTo = $this->request->getPost('assigned_to');
                    if ($newAssignedTo != $ticket['assigned_to']) {
                        $ticket['assigned_to'] = $newAssignedTo ?: null;
                        $ticket['assigned_at'] = $newAssignedTo ? date('Y-m-d H:i:s') : null;
                    }
                } else {
                    // Asesor solo puede actualizar estado y agregar comentarios
                    $ticket['status'] = $this->request->getPost('status');
                    
                    // Agregar comentario del asesor si se proporciona
                    $comment = $this->request->getPost('comment');
                    if ($comment) {
                        if (!isset($ticket['comments'])) {
                            $ticket['comments'] = [];
                        }
                        $ticket['comments'][] = [
                            'user_id' => $userId,
                            'user_name' => session()->get('username'),
                            'comment' => $comment,
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                    }
                }

                $ticket['updated_at'] = date('Y-m-d H:i:s');
                
                if ($ticket['status'] === 'closed') {
                    $ticket['closed_at'] = date('Y-m-d H:i:s');
                }

                break;
            }
        }

        file_put_contents($ticketsFile, json_encode($tickets, JSON_PRETTY_PRINT));

        return redirect()->to(base_url('admin/tickets/view/' . $id))->with('success', 'Ticket actualizado exitosamente');
    }

    public function delete($id)
    {
        // Solo admin puede eliminar tickets
        if (session()->get('role') !== 'admin') {
            return redirect()->to(base_url('admin/tickets'))->with('error', 'No autorizado');
        }

        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        $tickets = array_filter($tickets, function($ticket) use ($id) {
            return $ticket['id'] !== $id;
        });

        file_put_contents($ticketsFile, json_encode(array_values($tickets), JSON_PRETTY_PRINT));

        return redirect()->to(base_url('admin/tickets'))->with('success', 'Ticket eliminado exitosamente');
    }

    /**
     * Crear ticket desde conversación
     */
    public function createFromConversation()
    {
        $input = $this->request->getJSON();
        
        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        $newTicket = [
            'id' => uniqid(),
            'ticket_number' => $this->generateTicketNumber(),
            'platform' => 'whatsapp', // Por defecto, se puede cambiar
            'user_platform_id' => $input->sender,
            'user_name' => $input->user_name ?? 'Usuario',
            'user_phone' => $input->sender,
            'subject' => $input->subject ?? 'Consulta desde conversación',
            'description' => $input->description ?? 'Ticket creado automáticamente desde conversación',
            'status' => 'open',
            'priority' => $input->priority ?? 'medium',
            'assigned_to' => $input->assigned_to ?? null,
            'category' => $input->category ?? 'general',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'assigned_at' => $input->assigned_to ? date('Y-m-d H:i:s') : null,
            'conversation_id' => $input->sender // Vincular con la conversación
        ];

        $tickets[] = $newTicket;
        file_put_contents($ticketsFile, json_encode($tickets, JSON_PRETTY_PRINT));

        return $this->response->setJSON([
            'status' => 'success',
            'ticket_id' => $newTicket['id'],
            'ticket_number' => $newTicket['ticket_number']
        ]);
    }

    /**
     * Generar número de ticket único
     */
    private function generateTicketNumber()
    {
        return 'TK-' . date('Ymd') . '-' . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }

    /**
     * API para obtener estadísticas de tickets
     */
    public function getTicketStats()
    {
        if (!session()->get('isLoggedIn')) {
            return $this->response->setJSON(['error' => 'No autorizado']);
        }

        $role = session()->get('role');
        $userId = session()->get('user_id');

        $ticketsFile = WRITEPATH . 'tickets.json';
        $tickets = file_exists($ticketsFile) ? json_decode(file_get_contents($ticketsFile), true) : [];

        if ($role === 'advisor') {
            $tickets = array_filter($tickets, function($ticket) use ($userId) {
                return isset($ticket['assigned_to']) && $ticket['assigned_to'] == $userId;
            });
        }

        $stats = [
            'total' => count($tickets),
            'open' => count(array_filter($tickets, function($t) { return $t['status'] === 'open'; })),
            'in_progress' => count(array_filter($tickets, function($t) { return $t['status'] === 'in_progress'; })),
            'closed' => count(array_filter($tickets, function($t) { return $t['status'] === 'closed'; })),
            'urgent' => count(array_filter($tickets, function($t) { return $t['priority'] === 'urgent' && $t['status'] !== 'closed'; }))
        ];

        return $this->response->setJSON($stats);
    }
}