<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Shipment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class ShipmentController extends Controller
{
    /**
     * ثبت مرسوله ارسالی (type = 'send')
     */
    public function registerShipment(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'origin.country'          => 'required|string|max:255',
                'origin.city'             => 'required|string|max:255',
                'origin.address'          => 'nullable|string',
                'origin.coordinates'      => 'nullable|string',
                'destination.country'     => 'required|string|max:255',
                'destination.city'        => 'required|string|max:255',
                'destination.address'     => 'nullable|string',
                'destination.coordinates' => 'nullable|string',
                'title'                   => 'required|string|max:255',
                'description'             => 'nullable|string',
                'weight'                  => 'required|numeric|min:0.1',
                'category'                => 'required|string',
                'price_type'              => 'required|in:fixed,negotiable',
                'currency'                => 'required_if:price_type,fixed|in:IRT,USD,CAD,IQD',
                'amount'                  => 'required_if:price_type,fixed|numeric|min:0',
                'show_phone'              => 'boolean',
                'images.*'                => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors'  => $validator->errors(),
                ], 422);
            }

            DB::beginTransaction();

            $shipment                          = new Shipment();
            $shipment->user_id                 = auth()->id();
            $shipment->type                    = Shipment::TYPE_SEND; // 'send'
            $shipment->origin_country          = $request->input('origin.country');
            $shipment->origin_city             = $request->input('origin.city');
            $shipment->origin_address          = $request->input('origin.address');
            $shipment->origin_coordinates      = $request->input('origin.coordinates');
            $shipment->destination_country     = $request->input('destination.country');
            $shipment->destination_city        = $request->input('destination.city');
            $shipment->destination_address     = $request->input('destination.address');
            $shipment->destination_coordinates = $request->input('destination.coordinates');
            $shipment->title                   = $request->title;
            $shipment->description             = $request->description;
            $shipment->weight                  = $request->weight;
            $shipment->category                = $request->category;
            $shipment->price_type              = $request->price_type;
            $shipment->currency                = $request->price_type === 'fixed' ? $request->currency : null;
            $shipment->amount                  = $request->price_type === 'fixed' ? $request->amount : null;
            $shipment->show_phone              = filter_var($request->show_phone, FILTER_VALIDATE_BOOLEAN);

            $shipment->save();

            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    $filename = time() . '_' . uniqid() . '.' . $image->extension();
                    $image->move(public_path('uploads/shipments'), $filename);

                    $shipment->images()->create([
                        'image_path' => 'uploads/shipments/' . $filename,
                    ]);
                }
            }

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'مرسوله با موفقیت ثبت شد',
                'data'    => $shipment->load('images'),
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Shipment registration error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'خطا در ثبت مرسوله',
            ], 500);
        }
    }

    /**
     * ثبت سفر حمل (type = 'carry')
     */
    public function registerCarryTrip(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'origin.country'          => 'required|string|max:255',
                'origin.city'             => 'required|string|max:255',
                'origin.address'          => 'nullable|string',
                'origin.coordinates'      => 'nullable|string',
                'destination.country'     => 'required|string|max:255',
                'destination.city'        => 'required|string|max:255',
                'destination.address'     => 'nullable|string',
                'destination.coordinates' => 'nullable|string',
                'departure_date'          => 'required|date',
                'arrival_date'            => 'nullable|date|after:departure_date',
                'carry_weight_capacity'   => 'required|numeric|min:0.1',
                'price_type'              => 'required|in:fixed,negotiable',
                'currency'                => 'required_if:price_type,fixed|in:IRT,USD,CAD,IQD',
                'amount'                  => 'required_if:price_type,fixed|numeric|min:0',
                'trip_description'        => 'nullable|string',
                'show_phone'              => 'boolean',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors'  => $validator->errors(),
                ], 422);
            }

            $shipment                          = new Shipment();
            $shipment->user_id                 = auth()->id();
            $shipment->type                    = Shipment::TYPE_CARRY; // 'carry'
            $shipment->origin_country          = $request->input('origin.country');
            $shipment->origin_city             = $request->input('origin.city');
            $shipment->origin_address          = $request->input('origin.address');
            $shipment->origin_coordinates      = $request->input('origin.coordinates');
            $shipment->destination_country     = $request->input('destination.country');
            $shipment->destination_city        = $request->input('destination.city');
            $shipment->destination_address     = $request->input('destination.address');
            $shipment->destination_coordinates = $request->input('destination.coordinates');
            $shipment->departure_date          = $request->departure_date;
            $shipment->arrival_date            = $request->arrival_date;
            $shipment->carry_weight_capacity   = $request->carry_weight_capacity;
            $shipment->price_type              = $request->price_type;
            $shipment->currency                = $request->price_type === 'fixed' ? $request->currency : null;
            $shipment->amount                  = $request->price_type === 'fixed' ? $request->amount : null;
            $shipment->trip_description        = $request->trip_description;
            $shipment->show_phone              = filter_var($request->show_phone, FILTER_VALIDATE_BOOLEAN);

            $shipment->save();

            return response()->json([
                'success' => true,
                'message' => 'سفر با موفقیت ثبت شد',
                'data'    => $shipment,
            ], 201);

        } catch (\Exception $e) {
            Log::error('Carry trip registration error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'خطا در ثبت سفر',
            ], 500);
        }
    }

    /**
     * لیست همه (send + carry)
     */
    public function index(Request $request)
    {
        $shipments = Shipment::with(['user:id,name,phone', 'images'])
            ->where('is_active', true)
            ->latest()
            ->paginate(20);

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

    /**
     * لیست مرسوله‌های ارسالی (فقط type = 'send')
     */
    public function getSendShipments(Request $request)
    {
        $shipments = Shipment::with(['user:id,name,phone', 'images'])
            ->send() // استفاده از scope
            ->where('is_active', true)
            ->latest()
            ->paginate(20);

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

    /**
     * لیست سفرهای حمل (فقط type = 'carry')
     */
    public function getCarryTrips(Request $request)
    {
        $trips = Shipment::with('user:id,name,phone')
            ->carry() // استفاده از scope
            ->where('is_active', true)
            ->latest()
            ->paginate(20);

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

    /**
     * جزئیات یک مرسوله/سفر
     */
    public function show($id)
    {
        try {
            $shipment = Shipment::with(['user:id,name,phone', 'images'])
                ->findOrFail($id);

            return response()->json([
                'success' => true,
                'data'    => [
                    'id'                    => $shipment->id,
                    'type'                  => $shipment->type,
                    'title'                 => $shipment->title ?? $shipment->trip_description ?? 'بدون عنوان',
                    'description'           => $shipment->description ?? $shipment->trip_description,
                    'status'                => $shipment->status,
                    'is_active'             => $shipment->is_active,
                    'origin'                => [
                        'country'     => $shipment->origin_country,
                        'city'        => $shipment->origin_city,
                        'address'     => $shipment->origin_address,
                        'coordinates' => $shipment->origin_coordinates,
                    ],
                    'destination'           => [
                        'country'     => $shipment->destination_country,
                        'city'        => $shipment->destination_city,
                        'address'     => $shipment->destination_address,
                        'coordinates' => $shipment->destination_coordinates,
                    ],
                    'weight'                => $shipment->weight,
                    'carry_weight_capacity' => $shipment->carry_weight_capacity,
                    'category'              => $shipment->category,
                    'departure_date'        => $shipment->departure_date?->format('Y-m-d'),
                    'arrival_date'          => $shipment->arrival_date?->format('Y-m-d'),
                    'price_type'            => $shipment->price_type,
                    'currency'              => $shipment->currency,
                    'amount'                => $shipment->amount,
                    'show_phone'            => $shipment->show_phone,
                    'created_at'            => $shipment->created_at->toIso8601String(),
                    'images'                => $shipment->images->map(fn($img) => [
                        'id'  => $img->id,
                        'url' => $img->url,
                    ]),
                    'user'                  => [
                        'id'    => $shipment->user->id,
                        'name'  => $shipment->user->name,
                        'phone' => $shipment->show_phone ? $shipment->user->phone : null,
                    ],
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Shipment show error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات مرسوله',
            ], 500);
        }
    }

    /**
     * ویرایش
     */
    public function update(Request $request, $id)
    {
        try {
            $shipment = Shipment::findOrFail($id);

            // بررسی مالکیت
            if ($shipment->user_id !== auth()->id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'شما مجاز به ویرایش این مورد نیستید',
                ], 403);
            }

            // Validation بر اساس type
            if ($shipment->type === Shipment::TYPE_SEND) {
                $validator = Validator::make($request->all(), [
                    'origin.country'          => 'required|string|max:255',
                    'origin.city'             => 'required|string|max:255',
                    'origin.address'          => 'nullable|string',
                    'origin.coordinates'      => 'nullable|string',
                    'destination.country'     => 'required|string|max:255',
                    'destination.city'        => 'required|string|max:255',
                    'destination.address'     => 'nullable|string',
                    'destination.coordinates' => 'nullable|string',
                    'title'                   => 'required|string|max:255',
                    'description'             => 'nullable|string',
                    'weight'                  => 'required|numeric|min:0.1',
                    'category'                => 'required|string',
                    'price_type'              => 'required|in:fixed,negotiable',
                    'currency'                => 'required_if:price_type,fixed|in:IRT,USD,CAD,IQD',
                    'amount'                  => 'required_if:price_type,fixed|numeric|min:0',
                    'show_phone'              => 'boolean',
                ]);
            } else {
                $validator = Validator::make($request->all(), [
                    'origin.country'          => 'required|string|max:255',
                    'origin.city'             => 'required|string|max:255',
                    'origin.address'          => 'nullable|string',
                    'origin.coordinates'      => 'nullable|string',
                    'destination.country'     => 'required|string|max:255',
                    'destination.city'        => 'required|string|max:255',
                    'destination.address'     => 'nullable|string',
                    'destination.coordinates' => 'nullable|string',
                    'departure_date'          => 'required|date',
                    'arrival_date'            => 'nullable|date|after:departure_date',
                    'carry_weight_capacity'   => 'required|numeric|min:0.1',
                    'price_type'              => 'required|in:fixed,negotiable',
                    'currency'                => 'required_if:price_type,fixed|in:IRT,USD,CAD,IQD',
                    'amount'                  => 'required_if:price_type,fixed|numeric|min:0',
                    'trip_description'        => 'nullable|string',
                    'show_phone'              => 'boolean',
                ]);
            }

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors'  => $validator->errors(),
                ], 422);
            }

            DB::beginTransaction();

            // به‌روزرسانی فیلدهای مشترک
            $shipment->origin_country          = $request->input('origin.country');
            $shipment->origin_city             = $request->input('origin.city');
            $shipment->origin_address          = $request->input('origin.address');
            $shipment->origin_coordinates      = $request->input('origin.coordinates');
            $shipment->destination_country     = $request->input('destination.country');
            $shipment->destination_city        = $request->input('destination.city');
            $shipment->destination_address     = $request->input('destination.address');
            $shipment->destination_coordinates = $request->input('destination.coordinates');
            $shipment->price_type              = $request->price_type;
            $shipment->currency                = $request->price_type === 'fixed' ? $request->currency : null;
            $shipment->amount                  = $request->price_type === 'fixed' ? $request->amount : null;
            $shipment->show_phone              = filter_var($request->show_phone, FILTER_VALIDATE_BOOLEAN);

            // به‌روزرسانی فیلدهای خاص هر type
            if ($shipment->type === Shipment::TYPE_SEND) {
                $shipment->title       = $request->title;
                $shipment->description = $request->description;
                $shipment->weight      = $request->weight;
                $shipment->category    = $request->category;

                // مدیریت تصاویر جدید
                if ($request->hasFile('images')) {
                    foreach ($request->file('images') as $image) {
                        $filename = time() . '_' . uniqid() . '.' . $image->extension();
                        $image->move(public_path('uploads/shipments'), $filename);

                        $shipment->images()->create([
                            'image_path' => 'uploads/shipments/' . $filename,
                        ]);
                    }
                }
            } else {
                $shipment->departure_date        = $request->departure_date;
                $shipment->arrival_date          = $request->arrival_date;
                $shipment->carry_weight_capacity = $request->carry_weight_capacity;
                $shipment->trip_description      = $request->trip_description;
            }

            $shipment->save();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'با موفقیت به‌روزرسانی شد',
                'data'    => $shipment->load('images'),
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Shipment update error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی',
            ], 500);
        }
    }

    /**
     * لیست مرسوله‌های کاربر جاری
     */
    // لیست محموله‌های من
    public function myShipments(Request $request)
    {
        $query = Shipment::with('images')->where('user_id', auth()->id());

        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        $shipments = $query->latest()->paginate(10);

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

    /**
     * حذف مرسوله
     */
    public function destroy(Request $request, $id)
    {
        $user = $request->user();

        $shipment = Shipment::where('id', $id)
            ->where('user_id', $user->id)
            ->first();

        if (! $shipment) {
            return response()->json([
                'success' => false,
                'message' => 'مرسوله یافت نشد یا دسترسی ندارید',
            ], 404);
        }

        // حذف تصاویر از storage
        foreach ($shipment->images as $image) {
            Storage::disk('public')->delete($image->image_path);
        }

        $shipment->delete();

        return response()->json([
            'success' => true,
            'message' => 'مرسوله با موفقیت حذف شد',
        ]);
    }

    public function deleteImage(Request $request, $shipmentId, $imageId)
    {
        try {
            $shipment = Shipment::findOrFail($shipmentId);

            if ($shipment->user_id !== auth()->id()) {
                return response()->json([
                    'success' => false,
                    'message' => 'دسترسی غیرمجاز',
                ], 403);
            }

            $image = $shipment->images()->findOrFail($imageId);

            // حذف فایل
            if (file_exists(public_path($image->image_path))) {
                unlink(public_path($image->image_path));
            }

            $image->delete();

            return response()->json([
                'success' => true,
                'message' => 'تصویر حذف شد',
            ]);

        } catch (\Exception $e) {
            Log::error('Image delete error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف تصویر',
            ], 500);
        }
    }

}
