<?php

namespace App\Http\Controllers;

use App\Models\SystemSetting;
use App\Models\Ticket;
use App\Models\TicketReply;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;

class TicketController extends Controller
{
    public function index()
    {
        $tickets = Ticket::with(['replies.user'])
            ->where('user_id', auth()->id())
            ->latest()
            ->paginate(10);

        return response()->json($tickets);
    }

    public function show(Ticket $ticket)
    {
        // Ensure user can only see their own tickets
        if ($ticket->user_id != auth()->id()) {
            abort(403);
        }

        $ticket->load(['replies.user']);

        // Mark ticket as read when user opens it
        if (!$ticket->is_read) {
            $ticket->update(['is_read' => true]);
        }

        // Check if this is an API request (for refreshing ticket data)
        if (request()->wantsJson()) {
            return response()->json($ticket);
        }

        return Inertia::render('user/tickets/index', [
            'ticket' => $ticket,
        ]);
    }

    public function store(Request $request)
    {
        $image_max_upload_size = SystemSetting::getMaxUploadSize();
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'priority' => 'required|in:low,medium,high',
            'attachments.*' => "nullable|image|mimes:jpeg,png,jpg,gif,svg|max:$image_max_upload_size",
        ]);

        $ticket = new Ticket();
        $ticket->title = $validated['title'];
        $ticket->description = $validated['description'];
        $ticket->priority = $validated['priority'];
        $ticket->user_id = auth()->id();

        // Handle attachments
        if ($request->hasFile('attachments')) {
            $attachments = [];
            foreach ($request->file('attachments') as $file) {
                $path = $file->store('tickets', 'public');
                $attachments[] = [
                    'name' => $file->getClientOriginalName(),
                    'path' => $path,
                    'type' => 'image'
                ];
            }
            $ticket->attachments = $attachments;
        }

        $ticket->save();

        return back()->with('message', 'Ticket created successfully.');
    }

    public function reply(Request $request, Ticket $ticket)
    {
        // Debug logging for production issues
        Log::info('Ticket reply attempt', [
            'ticket_id' => $ticket->id,
            'user_id' => auth()->id(),
            'ticket_user_id' => $ticket->user_id,
            'request_method' => $request->method(),
            'user_agent' => $request->userAgent(),
        ]);

        // Ensure user can only reply to their own tickets
        if ($ticket->user_id != auth()->id()) {
            Log::warning('Ticket reply access denied', [
                'ticket_id' => $ticket->id,
                'user_id' => auth()->id(),
                'ticket_user_id' => $ticket->user_id,
            ]);
            abort(403, 'Access denied. You can only reply to your own tickets.');
        }

        $image_max_upload_size = SystemSetting::getMaxUploadSize();
        $validated = $request->validate([
            'content' => 'required|string',
            'attachments.*' => "nullable|image|mimes:jpeg,png,jpg,gif,svg|max:$image_max_upload_size",
        ]);

        $reply = new TicketReply();
        $reply->ticket_id = $ticket->id;
        $reply->user_id = auth()->id();
        $reply->content = $validated['content'];

        // Handle attachments
        if ($request->hasFile('attachments')) {
            $attachments = [];
            foreach ($request->file('attachments') as $file) {
                $path = $file->store('tickets', 'public');
                $attachments[] = [
                    'name' => $file->getClientOriginalName(),
                    'path' => $path,
                    'type' => 'image'
                ];
            }
            $reply->attachments = $attachments;
        }

        try {
            $reply->save();

            Log::info('Ticket reply saved successfully', [
                'reply_id' => $reply->id,
                'ticket_id' => $ticket->id,
                'user_id' => auth()->id(),
            ]);

            // Mark ticket as unread when admin replies
            if (auth()->user()->role === 'admin') {
                $ticket->update(['is_read' => false]);
            }

            // Return success response for Inertia.js
            if (request()->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Reply added successfully.',
                    'reply' => $reply->load('user')
                ]);
            }

            return back()->with('message', 'Reply added successfully.');
        } catch (\Exception $e) {
            Log::error('Failed to save ticket reply', [
                'ticket_id' => $ticket->id,
                'user_id' => auth()->id(),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            // Return error response for Inertia.js
            if (request()->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to add reply. Please try again.',
                    'error' => $e->getMessage()
                ], 422);
            }

            return back()->with('error', 'Failed to add reply. Please try again.');
        }
    }

    public function markAllAsRead()
    {
        // Mark all tickets for the authenticated user as read
        Ticket::where('user_id', auth()->id())->update(['is_read' => true]);

        return response()->json(['message' => 'All tickets marked as read']);
    }
}
