<?php

namespace App\Http\Controllers;

use App\Helpers\TenantHelper;
use App\Models\VendorUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SupportTicketController extends Controller
{
    public function create(Request $request)
    {
        $validated = $request->validate([
            'message' => 'required|string|max:1000',
        ]);

        $user    = Auth::guard('admin')->user();
        $adminId = Auth::guard('admin')->id();

        // ── Fetch vendor data from the tenant schema ──────────────────────────
        $restaurantName = null;
        $phone          = null;
        $vendorId       = null;

        $vendorUser = VendorUsers::where('user_id', $adminId)->first();
        if ($vendorUser) {
            $vendorId = $vendorUser->uuid;

            if ($vendorUser->schema_name) {
                TenantHelper::setSchema($vendorUser->schema_name);
                $vendor = DB::connection('pgsql_country')
                    ->table('vendors')
                    ->where('owner_id', $adminId)
                    ->first(['title', 'phone_number']);

                if ($vendor) {
                    $restaurantName = $vendor->title;
                    $phone          = $vendor->phone_number;
                }
            }
        }

        // Derive a contact_time bucket from the current hour to satisfy the DB check constraint
        $hour        = (int) now()->format('H');
        $contactTime = match(true) {
            $hour >= 6  && $hour < 12 => 'morning',
            $hour >= 12 && $hour < 17 => 'afternoon',
            default                   => 'evening',  // covers 17–24 and 0–5; 'night' not in constraint
        };

        $ticketData = [
            'ticket_id'       => 'PG-' . strtoupper(uniqid()),
            'vendor_id'       => $vendorId,
            'user_id'         => (string) $adminId,
            'email'           => $user->email,
            'restaurant_name' => $restaurantName,
            'phone'           => $phone,
            'contact_time'    => $contactTime,
            'issue_type'      => 'general',
            'description'     => $validated['message'],
            'message'         => $validated['message'],
            'status'          => 'pending',
            'priority'        => 'normal',
            'ip_address'      => TenantHelper::getClientIp($request),
            'user_agent'      => $request->userAgent(),
            'created_at'      => now(),
            'updated_at'      => now(),
        ];

        DB::table('support_tickets')->insert($ticketData);

        Log::info('Support ticket created', [
            'ticket_id' => $ticketData['ticket_id'],
            'email'     => $user->email,
            'vendor_id' => $vendorId,
        ]);

        return response()->json([
            'success'   => true,
            'ticket_id' => $ticketData['ticket_id'],
        ]);
    }
}
