<?php

namespace App\Http\Controllers\Api;

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

class SupportController extends Controller
{
    /**
     * Get active support channels.
     */
    public function channels()
    {
        $channels = SupportChannel::where('is_active', true)->get();
        return response()->json([
            'channels' => $channels,
        ]);
    }

    /**
     * Get user's support tickets.
     */
    public function tickets(Request $request)
    {
        $tickets = SupportTicket::where('user_id', $request->user()->id)
            ->orderBy('created_at', 'desc')
            ->get();
            
        return response()->json([
            'tickets' => $tickets,
        ]);
    }

    /**
     * Create a new support ticket.
     */
    public function createTicket(Request $request)
    {
        $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string'],
            'priority' => ['nullable', 'string', 'in:low,medium,high'],
        ]);

        $ticket = SupportTicket::create([
            'user_id' => $request->user()->id,
            'subject' => $request->subject,
            'message' => $request->message,
            'priority' => $request->priority ?? 'medium',
            'status' => 'open',
        ]);

        return response()->json([
            'message' => 'Support ticket created successfully.',
            'ticket' => $ticket,
        ], 201);
    }

    /**
     * Get specific setting by key.
     */
    public function setting($key)
    {
        $setting = Setting::where('key', $key)->first();
        return response()->json([
            'key' => $key,
            'value' => $setting ? $setting->value : null,
        ]);
    }

    /**
     * Get Flutterwave public configuration (safe to expose to client).
     * Secret key is intentionally excluded.
     */
    public function flutterwaveConfig()
    {
        $publicKey  = Setting::where('key', 'flutterwave_public_key')->value('value');
        $isTestMode = Setting::where('key', 'flutterwave_test_mode')->value('value');

        if (!$publicKey) {
            return response()->json(['message' => 'Flutterwave is not configured.'], 503);
        }

        return response()->json([
            'public_key'   => $publicKey,
            'is_test_mode' => $isTestMode === 'true',
        ]);
    }
}
