<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\AgentTransaction;
use App\Models\AgentReview;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AgentController extends Controller
{
    public function getGovernorates()
    {
        $governorates = [
            'بغداد', 'البصرة', 'الموصل', 'أربيل', 'النجف', 'كربلاء',
            'بابل', 'الأنبار', 'ديالى', 'واسط', 'ميسان', 'ذي قار',
            'صلاح الدين', 'كركوك', 'دهوك', 'السليمانية', 'المثنى', 'القادسية'
        ];

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

    public function getAgentsByGovernorate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'governorate' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'بيانات غير صحيحة',
                'errors' => $validator->errors()
            ], 400);
        }

        $agents = Agent::where('governorate', $request->governorate)
            ->where('is_active', true)
            ->with(['reviews' => function($query) {
                $query->latest()->limit(5);
            }])
            ->get()
            ->map(function($agent) {
                return [
                    'id' => $agent->id,
                    'name' => $agent->name,
                    'phone' => $agent->phone,
                    'governorate' => $agent->governorate,
                    'city' => $agent->city,
                    'type' => $agent->type,
                    'rating' => $agent->getAverageRating(),
                    'total_reviews' => $agent->getTotalReviews(),
                    'total_transactions' => $agent->total_transactions,
                    'is_premium' => $agent->isPremium(),
                    'profile_image' => $agent->profile_image,
                ];
            });

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

    public function getAgentDetails($id)
    {
        $agent = Agent::with(['reviews.user', 'transactions'])
            ->find($id);

        if (!$agent) {
            return response()->json([
                'success' => false,
                'message' => 'الوكيل غير موجود'
            ], 404);
        }

        $recentReviews = $agent->reviews()
            ->with('user')
            ->latest()
            ->limit(10)
            ->get()
            ->map(function($review) {
                return [
                    'id' => $review->id,
                    'user_name' => $review->user->name,
                    'rating' => $review->rating,
                    'comment' => $review->comment,
                    'created_at' => $review->created_at->format('Y-m-d H:i'),
                ];
            });

        $agentData = [
            'id' => $agent->id,
            'name' => $agent->name,
            'phone' => $agent->phone,
            'email' => $agent->email,
            'governorate' => $agent->governorate,
            'city' => $agent->city,
            'address' => $agent->address,
            'type' => $agent->type,
            'rating' => $agent->getAverageRating(),
            'total_reviews' => $agent->getTotalReviews(),
            'total_transactions' => $agent->total_transactions,
            'is_premium' => $agent->isPremium(),
            'profile_image' => $agent->profile_image,
            'description' => $agent->description,
            'working_hours' => $agent->working_hours,
            'payment_methods' => $agent->payment_methods,
            'recent_reviews' => $recentReviews,
        ];

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

    public function createTransaction(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|exists:agents,id',
            'amount' => 'required|numeric|min:0.01',
            'gems_amount' => 'required|integer|min:1',
            'payment_method' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'بيانات غير صحيحة',
                'errors' => $validator->errors()
            ], 400);
        }

        $agent = Agent::find($request->agent_id);
        if (!$agent || !$agent->is_active) {
            return response()->json([
                'success' => false,
                'message' => 'الوكيل غير متاح'
            ], 400);
        }

        $transaction = AgentTransaction::create([
            'agent_id' => $request->agent_id,
            'user_id' => auth()->id(),
            'amount' => $request->amount,
            'gems_amount' => $request->gems_amount,
            'payment_method' => $request->payment_method,
            'transaction_id' => 'TXN' . Str::random(10),
            'notes' => $request->notes,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم إنشاء المعاملة بنجاح',
            'data' => [
                'transaction_id' => $transaction->transaction_id,
                'amount' => $transaction->amount,
                'gems_amount' => $transaction->gems_amount,
                'status' => $transaction->status,
                'created_at' => $transaction->created_at->format('Y-m-d H:i'),
            ]
        ]);
    }

    public function getMyTransactions()
    {
        $transactions = AgentTransaction::where('user_id', auth()->id())
            ->with('agent')
            ->latest()
            ->get()
            ->map(function($transaction) {
                return [
                    'id' => $transaction->id,
                    'transaction_id' => $transaction->transaction_id,
                    'agent_name' => $transaction->agent->name,
                    'amount' => $transaction->amount,
                    'gems_amount' => $transaction->gems_amount,
                    'status' => $transaction->status,
                    'payment_method' => $transaction->payment_method,
                    'created_at' => $transaction->created_at->format('Y-m-d H:i'),
                ];
            });

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

    public function addReview(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|exists:agents,id',
            'transaction_id' => 'required|exists:agent_transactions,id',
            'rating' => 'required|integer|min:1|max:5',
            'comment' => 'nullable|string|max:500',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'بيانات غير صحيحة',
                'errors' => $validator->errors()
            ], 400);
        }

        // تحقق من أن المعاملة مكتملة
        $transaction = AgentTransaction::where('id', $request->transaction_id)
            ->where('user_id', auth()->id())
            ->where('status', 'completed')
            ->first();

        if (!$transaction) {
            return response()->json([
                'success' => false,
                'message' => 'المعاملة غير موجودة أو غير مكتملة'
            ], 400);
        }

        // تحقق من عدم وجود تقييم سابق
        $existingReview = AgentReview::where('transaction_id', $request->transaction_id)
            ->where('user_id', auth()->id())
            ->first();

        if ($existingReview) {
            return response()->json([
                'success' => false,
                'message' => 'لقد قمت بتقييم هذه المعاملة مسبقاً'
            ], 400);
        }

        $review = AgentReview::create([
            'agent_id' => $request->agent_id,
            'user_id' => auth()->id(),
            'transaction_id' => $request->transaction_id,
            'rating' => $request->rating,
            'comment' => $request->comment,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم إضافة التقييم بنجاح',
            'data' => $review
        ]);
    }
}
