<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\V1\Concerns\RespondsWithApi;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SupportController extends Controller
{
    use RespondsWithApi;

    public function tickets(Request $request)
    {
        return $this->ok(DB::table('support_tickets')->where('user_id', $request->user()->id)->latest('id')->paginate(20));
    }

    public function storeTicket(Request $request)
    {
        $data = $request->validate([
            'booking_id' => ['nullable', 'integer'],
            'category' => ['required', 'string', 'max:80'],
            'priority' => ['nullable', 'in:low,normal,high,urgent'],
            'message' => ['required', 'string', 'max:2000'],
        ]);

        $ticketId = DB::table('support_tickets')->insertGetId([
            'ticket_number' => 'TK-' . now()->format('Ymd') . '-' . strtoupper(Str::random(6)),
            'user_id' => $request->user()->id,
            'booking_id' => $data['booking_id'] ?? null,
            'category' => $data['category'],
            'priority' => $data['priority'] ?? 'normal',
            'status' => 'open',
            'first_response_due_at' => now()->addHours(2),
            'resolution_due_at' => now()->addDay(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::table('support_messages')->insert([
            'support_ticket_id' => $ticketId,
            'sender_type' => 'customer',
            'sender_id' => $request->user()->id,
            'message' => $data['message'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return $this->ok($this->loadTicket($ticketId), 'Ticket created.', [], 201);
    }

    public function showTicket(Request $request, int $ticket)
    {
        $exists = DB::table('support_tickets')->where('id', $ticket)->where('user_id', $request->user()->id)->exists();

        return $exists ? $this->ok($this->loadTicket($ticket)) : $this->fail('TICKET_NOT_FOUND', 'Ticket not found.', [], 404);
    }

    public function message(Request $request, int $ticket)
    {
        $data = $request->validate([
            'message' => ['required', 'string', 'max:2000'],
            'attachment_path' => ['nullable', 'string', 'max:255'],
        ]);

        $exists = DB::table('support_tickets')->where('id', $ticket)->where('user_id', $request->user()->id)->exists();

        if (! $exists) {
            return $this->fail('TICKET_NOT_FOUND', 'Ticket not found.', [], 404);
        }

        DB::table('support_messages')->insert([
            'support_ticket_id' => $ticket,
            'sender_type' => 'customer',
            'sender_id' => $request->user()->id,
            'message' => $data['message'],
            'attachment_path' => $data['attachment_path'] ?? null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return $this->ok($this->loadTicket($ticket), 'Message sent.');
    }

    public function close(Request $request, int $ticket)
    {
        DB::table('support_tickets')->where('id', $ticket)->where('user_id', $request->user()->id)->update([
            'status' => 'closed',
            'updated_at' => now(),
        ]);

        return $this->ok([], 'Ticket closed.');
    }

    private function loadTicket(int $ticket): array
    {
        $row = (array) DB::table('support_tickets')->where('id', $ticket)->first();
        $row['messages'] = DB::table('support_messages')->where('support_ticket_id', $ticket)->orderBy('id')->get();

        return $row;
    }
}
