<?php

namespace App\Http\Controllers\Business;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use Illuminate\Http\Request;

class SupportController extends Controller
{
    /**
     * Display support tickets
     */
    public function index()
    {
        $business = auth()->user()->business;

        $tickets = SupportTicket::where('business_id', $business->id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        $stats = [
            'total' => SupportTicket::where('business_id', $business->id)->count(),
            'open' => SupportTicket::where('business_id', $business->id)->where('status', 'open')->count(),
            'pending' => SupportTicket::where('business_id', $business->id)->where('status', 'pending')->count(),
            'resolved' => SupportTicket::where('business_id', $business->id)->where('status', 'resolved')->count(),
        ];

        return view('business.support.tickets', compact('tickets', 'stats'));
    }

    /**
     * Show create ticket form
     */
    public function create()
    {
        return view('business.support.create');
    }

    /**
     * Store new ticket
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'category' => 'required|in:technical,billing,general,feature_request',
            'priority' => 'required|in:low,medium,high,urgent',
            'description' => 'required|string',
            'attachments' => 'nullable|array',
            'attachments.*' => 'file|max:5120',
        ]);

        $business = auth()->user()->business;

        $attachments = [];
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $path = $file->store('support/attachments', 'public');
                $attachments[] = $path;
            }
        }

        $ticket = SupportTicket::create([
            'business_id' => $business->id,
            'user_id' => auth()->id(),
            'ticket_number' => 'TKT-' . strtoupper(uniqid()),
            'subject' => $validated['subject'],
            'category' => $validated['category'],
            'priority' => $validated['priority'],
            'description' => $validated['description'],
            'attachments' => json_encode($attachments),
            'status' => 'open',
        ]);

        // Send notification about new support ticket
        $channels = config_value('notifications.channels.support_ticket_created', ['database']);
        notify(auth()->user(), 'support_ticket_created', [
            'ticket_number' => $ticket->ticket_number,
            'subject' => $ticket->subject,
            'priority' => $ticket->priority,
            'action_url' => route('business.support.show', $ticket->id),
        ], $channels);

        return redirect()->route('business.support.show', $ticket->id)
            ->with('success', 'Support ticket created successfully!');
    }

    /**
     * Show ticket details
     */
    public function show($id)
    {
        $business = auth()->user()->business;

        $ticket = SupportTicket::where('business_id', $business->id)
            ->with('replies')
            ->findOrFail($id);

        return view('business.support.show', compact('ticket'));
    }

    /**
     * Reply to ticket
     */
    public function reply(Request $request, $id)
    {
        $request->validate([
            'message' => 'required|string',
            'attachments' => 'nullable|array',
            'attachments.*' => 'file|max:5120',
        ]);

        $business = auth()->user()->business;

        $ticket = SupportTicket::where('business_id', $business->id)
            ->findOrFail($id);

        $attachments = [];
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $path = $file->store('support/replies', 'public');
                $attachments[] = $path;
            }
        }

        $ticket->replies()->create([
            'user_id' => auth()->id(),
            'message' => $request->message,
            'attachments' => json_encode($attachments),
            'is_staff_reply' => false,
        ]);

        $ticket->update(['status' => 'pending']);

        return back()->with('success', 'Reply added successfully!');
    }

    /**
     * Close ticket
     */
    public function close($id)
    {
        $business = auth()->user()->business;

        $ticket = SupportTicket::where('business_id', $business->id)
            ->findOrFail($id);

        $ticket->update([
            'status' => 'closed',
            'closed_at' => now()
        ]);

        return back()->with('success', 'Ticket closed successfully!');
    }
}
