<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SupportSetting;
use App\Models\SupportTicket;
use App\Models\SupportTicketReply;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SupportController extends Controller
{
    /**
     * Get support settings and contact info
     */
    public function getSettings()
    {
        $settings = SupportSetting::current();
        
        return response()->json([
            'support_email' => $settings->support_email ?? 'support@clx.com',
            'support_phone' => $settings->support_phone ?? '+1234567890',
            'whatsapp_number' => $settings->support_phone ?? '+1234567890',
            'ticket_enabled' => $settings->ticket_enabled ?? true,
            'chat_enabled' => $settings->chat_enabled ?? false,
            'email_enabled' => $settings->email_enabled ?? true,
            'call_enabled' => $settings->call_enabled ?? true,
            'business_hours' => $settings->business_hours ?? [],
            'avg_response_time_hours' => $settings->avg_response_time_hours ?? 24,
            
            // Location Settings
            'location_provider' => \App\Models\Setting::where('key', 'location_provider')->value('value') ?? 'osm',
            'google_maps_api_key' => \App\Models\Setting::where('key', 'google_maps_api_key')->value('value') ?? '',
            'google_maps_geocoding_enabled' => \App\Models\Setting::where('key', 'google_maps_geocoding_enabled')->value('value') ?? '0',
            'google_maps_places_enabled' => \App\Models\Setting::where('key', 'google_maps_places_enabled')->value('value') ?? '0',
        ]);
    }

    /**
     * Get FAQs
     */
    public function getFAQs()
    {
        // For now, return hardcoded FAQs. Later this can be managed from admin
        $faqs = [
            [
                'id' => 1,
                'category' => 'Getting Started',
                'question' => 'How do I post an ad?',
                'answer' => 'To post an ad, tap the "+" button on the home screen, select a category, fill in the details, upload photos, and publish. You can manage your ads from the "My Ads" section.',
                'order' => 1
            ],
            [
                'id' => 2,
                'category' => 'Premium Features',
                'question' => 'How do I boost my ad?',
                'answer' => 'You can boost your ad from the ad details page by tapping "Boost Ad". Choose a package that fits your needs and complete the payment. Boosted ads get more visibility and appear at the top of search results.',
                'order' => 2
            ],
            [
                'id' => 3,
                'category' => 'Payments',
                'question' => 'What payment methods are accepted?',
                'answer' => 'We accept credit/debit cards, PayPal, and various local payment methods depending on your region. All payments are processed securely through our payment gateway.',
                'order' => 3
            ],
            [
                'id' => 4,
                'category' => 'Safety',
                'question' => 'How do I report a suspicious ad?',
                'answer' => 'Open the ad, tap the three-dot menu, and select "Report Ad". Choose the reason for reporting and submit. Our team will review it within 24 hours.',
                'order' => 4
            ],
            [
                'id' => 5,
                'category' => 'Ad Management',
                'question' => 'Can I edit my ad after posting?',
                'answer' => 'Yes! Go to "My Ads", select the ad you want to edit, tap the edit icon, make your changes, and save. Note that some changes may require re-approval.',
                'order' => 5
            ],
            [
                'id' => 6,
                'category' => 'Account',
                'question' => 'How do I verify my account?',
                'answer' => 'Go to Account Settings > Verification. You can verify your account through email, phone number, or government ID. Verified accounts get higher trust ratings.',
                'order' => 6
            ],
            [
                'id' => 7,
                'category' => 'Messaging',
                'question' => 'How do I contact a seller?',
                'answer' => 'Open the ad and tap "Contact Seller" or use the chat icon. You can send messages, make offers, and negotiate directly through our secure messaging system.',
                'order' => 7
            ],
            [
                'id' => 8,
                'category' => 'Premium Plans',
                'question' => 'What are the benefits of premium plans?',
                'answer' => 'Premium plans offer more ads, priority support, verified badge, advanced analytics, and ad boosting credits. Choose a plan that matches your selling needs.',
                'order' => 8
            ]
        ];

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

    /**
     * Get support ticket categories
     */
    public function getCategories()
    {
        $categories = [
            'Account Issues',
            'Payment Problems',
            'Ad Posting Issues',
            'Technical Problems',
            'Report Abuse',
            'Feature Request',
            'Other'
        ];

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

    /**
     * Submit a support ticket
     */
    public function createTicket(Request $request)
    {
        $validated = $request->validate([
            'category' => 'required|string',
            'subject' => 'required|string|max:255',
            'description' => 'required|string|min:10',
            'attachments.*' => 'nullable|file|max:5120|mimes:jpg,jpeg,png,pdf'
        ]);

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

        $ticket = SupportTicket::create([
            'user_id' => auth()->id(),
            'ticket_number' => SupportTicket::generateTicketNumber(),
            'category' => $validated['category'],
            'subject' => $validated['subject'],
            'description' => $validated['description'],
            'status' => 'open',
            'priority' => 'medium',
            'attachments' => $attachments
        ]);

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

    /**
     * Get user's support tickets
     */
    public function getMyTickets(Request $request)
    {
        $tickets = SupportTicket::where('user_id', auth()->id())
            ->with('replies')
            ->latest()
            ->paginate(20);

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

    /**
     * Get specific ticket details
     */
    public function getTicket($id)
    {
        $ticket = SupportTicket::where('user_id', auth()->id())
            ->where('id', $id)
            ->with(['replies.user', 'assignedAdmin'])
            ->firstOrFail();

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

    /**
     * Reply to a ticket
     */
    public function replyToTicket(Request $request, $id)
    {
        $ticket = SupportTicket::where('user_id', auth()->id())
            ->findOrFail($id);

        $validated = $request->validate([
            'message' => 'required|string',
            'attachments.*' => 'nullable|file|max:5120|mimes:jpg,jpeg,png,pdf'
        ]);

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

        $reply = SupportTicketReply::create([
            'ticket_id' => $ticket->id,
            'user_id' => auth()->id(),
            'is_admin' => false,
            'message' => $validated['message'],
            'attachments' => $attachments
        ]);

        // Update ticket status to in_progress if it was resolved/closed
        if (in_array($ticket->status, ['resolved', 'closed'])) {
            $ticket->update(['status' => 'in_progress']);
        }

        return response()->json([
            'message' => 'Reply sent successfully',
            'reply' => $reply
        ]);
    }
}
