<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\TicketAgent;
use App\Models\Lead;
use App\Models\Device;
use App\Services\TicketRoutingService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class WaTicketApiController extends Controller
{
    protected $routingService;

    public function __construct(TicketRoutingService $routingService)
    {
        $this->routingService = $routingService;
    }

    /**
     * Create a new support ticket via API
     * 
     * POST /api/waticket/tickets
     * 
     * Headers:
     *   X-API-Key: your-api-key
     *   X-Device-ID: your-device-id
     * 
     * Body:
     * {
     *   "customer_phone": "1234567890",
     *   "customer_name": "John Doe",
     *   "customer_email": "john@example.com",
     *   "subject": "Order Support",
     *   "description": "Need help with order #12345",
     *   "priority": "medium",
     *   "category": "order_support",
     *   "external_reference": "POS-ORDER-12345"
     * }
     */
    public function createTicket(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'customer_phone' => 'required|string|max:20',
            'customer_name' => 'nullable|string|max:255',
            'customer_email' => 'nullable|email|max:255',
            'subject' => 'required|string|max:255',
            'description' => 'required|string|max:5000',
            'priority' => 'nullable|in:low,medium,high,urgent',
            'category' => 'nullable|string|max:50',
            'external_reference' => 'nullable|string|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $deviceId = $request->header('X-Device-ID');
            
            // Verify device exists and belongs to API key user
            $device = Device::where('id', $deviceId)
                ->where('user_id', $request->user()->id)
                ->first();

            if (!$device) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid device ID',
                ], 403);
            }

            $ticket = SupportTicket::create([
                'device_id' => $deviceId,
                'customer_phone' => $request->customer_phone,
                'customer_name' => $request->customer_name,
                'customer_email' => $request->customer_email,
                'subject' => htmlspecialchars($request->subject, ENT_QUOTES, 'UTF-8'),
                'description' => htmlspecialchars($request->description, ENT_QUOTES, 'UTF-8'),
                'status' => 'new',
                'priority' => $request->priority ?? 'medium',
                'category' => $request->category,
                'external_reference' => $request->external_reference,
                'created_by' => $request->user()->id,
            ]);

            // Add initial message
            $ticket->addMessage(
                htmlspecialchars($request->description, ENT_QUOTES, 'UTF-8'),
                'customer',
                null,
                'text'
            );

            // Create or update lead
            $this->routingService->createOrUpdateLead(
                $deviceId,
                $request->customer_phone,
                $request->customer_name,
                $ticket
            );

            // Auto-assign if enabled
            $this->routingService->autoAssignTicket($ticket);

            // Reload to get relationships
            $ticket->load(['assignedAgent', 'messages']);

            return response()->json([
                'success' => true,
                'message' => 'Ticket created successfully',
                'data' => [
                    'ticket_id' => $ticket->id,
                    'ticket_number' => $ticket->ticket_number,
                    'status' => $ticket->status,
                    'priority' => $ticket->priority,
                    'assigned_to' => $ticket->assignedAgent ? $ticket->assignedAgent->user->name : null,
                    'created_at' => $ticket->created_at->toIso8601String(),
                ],
            ], 201);

        } catch (\Exception $e) {
            Log::error('API Ticket Creation Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to create ticket',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Get ticket details
     * 
     * GET /api/waticket/tickets/{ticket_number}
     */
    public function getTicket(Request $request, $ticketNumber)
    {
        try {
            $deviceId = $request->header('X-Device-ID');
            
            $ticket = SupportTicket::where('ticket_number', $ticketNumber)
                ->where('device_id', $deviceId)
                ->with(['assignedAgent.user', 'messages', 'lead'])
                ->first();

            if (!$ticket) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ticket not found',
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'ticket_number' => $ticket->ticket_number,
                    'customer_phone' => $ticket->customer_phone,
                    'customer_name' => $ticket->customer_name,
                    'customer_email' => $ticket->customer_email,
                    'subject' => $ticket->subject,
                    'description' => $ticket->description,
                    'status' => $ticket->status,
                    'priority' => $ticket->priority,
                    'category' => $ticket->category,
                    'external_reference' => $ticket->external_reference,
                    'assigned_to' => $ticket->assignedAgent ? $ticket->assignedAgent->user->name : null,
                    'created_at' => $ticket->created_at->toIso8601String(),
                    'updated_at' => $ticket->updated_at->toIso8601String(),
                    'messages_count' => $ticket->messages->count(),
                    'lead_score' => $ticket->lead?->lead_score,
                ],
            ]);

        } catch (\Exception $e) {
            Log::error('API Get Ticket Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve ticket',
            ], 500);
        }
    }

    /**
     * Add message to ticket
     * 
     * POST /api/waticket/tickets/{ticket_number}/messages
     * 
     * Body:
     * {
     *   "message": "Here is an update on your order...",
     *   "sender_type": "agent"
     * }
     */
    public function addMessage(Request $request, $ticketNumber)
    {
        $validator = Validator::make($request->all(), [
            'message' => 'required|string|max:5000',
            'sender_type' => 'nullable|in:agent,customer,system',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $deviceId = $request->header('X-Device-ID');
            
            $ticket = SupportTicket::where('ticket_number', $ticketNumber)
                ->where('device_id', $deviceId)
                ->first();

            if (!$ticket) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ticket not found',
                ], 404);
            }

            $ticket->addMessage(
                htmlspecialchars($request->message, ENT_QUOTES, 'UTF-8'),
                $request->sender_type ?? 'agent',
                $request->user()->id,
                'text'
            );

            return response()->json([
                'success' => true,
                'message' => 'Message added successfully',
            ]);

        } catch (\Exception $e) {
            Log::error('API Add Message Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to add message',
            ], 500);
        }
    }

    /**
     * Update ticket status
     * 
     * PATCH /api/waticket/tickets/{ticket_number}/status
     * 
     * Body:
     * {
     *   "status": "resolved"
     * }
     */
    public function updateStatus(Request $request, $ticketNumber)
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required|in:new,open,pending,resolved,closed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $deviceId = $request->header('X-Device-ID');
            
            $ticket = SupportTicket::where('ticket_number', $ticketNumber)
                ->where('device_id', $deviceId)
                ->first();

            if (!$ticket) {
                return response()->json([
                    'success' => false,
                    'message' => 'Ticket not found',
                ], 404);
            }

            $ticket->changeStatus($request->status, $request->user()->id);

            return response()->json([
                'success' => true,
                'message' => 'Status updated successfully',
                'data' => [
                    'ticket_number' => $ticket->ticket_number,
                    'status' => $ticket->status,
                ],
            ]);

        } catch (\Exception $e) {
            Log::error('API Update Status Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to update status',
            ], 500);
        }
    }

    /**
     * List tickets with filters
     * 
     * GET /api/waticket/tickets
     * 
     * Query params:
     *   ?status=open&priority=high&limit=20&page=1
     */
    public function listTickets(Request $request)
    {
        try {
            $deviceId = $request->header('X-Device-ID');
            
            $query = SupportTicket::where('device_id', $deviceId)
                ->with(['assignedAgent.user']);

            // Apply filters
            if ($request->has('status')) {
                $query->byStatus($request->status);
            }

            if ($request->has('priority')) {
                $query->byPriority($request->priority);
            }

            if ($request->has('external_reference')) {
                $query->where('external_reference', $request->external_reference);
            }

            if ($request->has('customer_phone')) {
                $query->where('customer_phone', $request->customer_phone);
            }

            $limit = min($request->get('limit', 20), 100);
            $tickets = $query->orderBy('created_at', 'desc')->paginate($limit);

            return response()->json([
                'success' => true,
                'data' => $tickets->items(),
                'pagination' => [
                    'current_page' => $tickets->currentPage(),
                    'total_pages' => $tickets->lastPage(),
                    'per_page' => $tickets->perPage(),
                    'total' => $tickets->total(),
                ],
            ]);

        } catch (\Exception $e) {
            Log::error('API List Tickets Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve tickets',
            ], 500);
        }
    }

    /**
     * Get statistics
     * 
     * GET /api/waticket/statistics
     */
    public function getStatistics(Request $request)
    {
        try {
            $deviceId = $request->header('X-Device-ID');

            $stats = [
                'total' => SupportTicket::where('device_id', $deviceId)->count(),
                'by_status' => [
                    'new' => SupportTicket::where('device_id', $deviceId)->byStatus('new')->count(),
                    'open' => SupportTicket::where('device_id', $deviceId)->open()->count(),
                    'pending' => SupportTicket::where('device_id', $deviceId)->byStatus('pending')->count(),
                    'resolved' => SupportTicket::where('device_id', $deviceId)->byStatus('resolved')->count(),
                    'closed' => SupportTicket::where('device_id', $deviceId)->byStatus('closed')->count(),
                ],
                'by_priority' => [
                    'low' => SupportTicket::where('device_id', $deviceId)->byPriority('low')->count(),
                    'medium' => SupportTicket::where('device_id', $deviceId)->byPriority('medium')->count(),
                    'high' => SupportTicket::where('device_id', $deviceId)->byPriority('high')->count(),
                    'urgent' => SupportTicket::where('device_id', $deviceId)->byPriority('urgent')->count(),
                ],
                'unassigned' => SupportTicket::where('device_id', $deviceId)->unassigned()->count(),
                'agents' => [
                    'total' => TicketAgent::where('device_id', $deviceId)->count(),
                    'online' => TicketAgent::where('device_id', $deviceId)->online()->count(),
                    'available' => TicketAgent::where('device_id', $deviceId)->available()->count(),
                ],
                'leads' => [
                    'total' => Lead::where('device_id', $deviceId)->count(),
                    'new' => Lead::where('device_id', $deviceId)->new()->count(),
                    'qualified' => Lead::where('device_id', $deviceId)->qualified()->count(),
                    'converted' => Lead::where('device_id', $deviceId)->converted()->count(),
                ],
            ];

            return response()->json([
                'success' => true,
                'data' => $stats,
            ]);

        } catch (\Exception $e) {
            Log::error('API Statistics Error: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve statistics',
            ], 500);
        }
    }
}
