<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Address;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddressController extends Controller
{
    /**
     * إضافة عنوان جديد
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addAddress(Request $request)
    {
        try {
            $validated = $request->validate([
                'address_line_1' => 'required|string|max:255',
                'address_line_2' => 'nullable|string|max:255',
                'city'           => 'nullable|string|max:100',
                'country'        => 'nullable|string|max:100',
                'postal_code'    => 'nullable|string|max:20',
                'whatsapp'       => 'nullable|string|max:20',
                'phone'          => 'nullable|string|max:20',
                'email'          => 'nullable|email|max:100',
                'name'           => 'nullable|string|max:100',
                'is_default'     => 'boolean',
            ]);

            $user = $request->user();

            if (!$user) {
                return response()->json([
                    'status'  => false,
                    'message' => 'غير مصرح'
                ], 401);
            }

            if (!empty($validated['is_default']) && $validated['is_default'] === true) {
                $user->addresses()->update(['is_default' => false]);
            }

            $address = $user->addresses()->create([
                'user_id'       => $user->id,
                'address_line_1' => $validated['address_line_1'],
                'address_line_2' => $validated['address_line_2'] ?? null,
                'city'          => $validated['city'],
                'country'       => $validated['country'],
                'postal_code'   => $validated['postal_code'] ?? null,
                'is_default'    => $validated['is_default'] ?? false,
                'whatsapp'      => $validated['whatsapp'] ?? null,
                'email'         => $validated['email'] ?? null,
                'phone'         => $validated['phone'] ?? null,
                'name'          => $validated['name'] ?? null,
            ]);

            return response()->json([
                'status'  => true,
                'message' => 'تم إضافة العنوان بنجاح',
                'address' => $address,
            ], 200);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status'  => false,
                'message' => 'خطأ في التحقق من البيانات',
                'errors'  => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status'  => false,
                'message' => 'حدث خطأ غير متوقع',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * جلب جميع العناوين
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddresses(Request $request)
    {
        /** @var \App\Models\User|\Laravel\Sanctum\HasApiTokens $user */
        $user = $request->user();

        if (!$user) {
            return response()->json(['message' => 'غير مصرح'], 401);
        }

        $addresses = $user->addresses()->get();

        return response()->json([
            'message' => 'تم جلب العناوين بنجاح',
            'addresses' => $addresses,
        ]);
    }

    public function getAddress($id)
    {
        /** @var \App\Models\User|\Laravel\Sanctum\HasApiTokens $user */
        $user = auth()->user();

        if (!$user) {
            return response()->json(['message' => 'غير مصرح'], 401);
        }

        $address = Address::where('id', $id)->where('user_id', $user->id)->first();

        if (!$address) {
            return response()->json(['message' => 'العنوان غير موجود أو لا يتبع لك'], 404);
        }

        return response()->json([
            'message' => 'تم جلب العنوان بنجاح',
            'address' => $address,
        ]);
    }

    /**
     * حذف عنوان
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAddress(Request $request)
    {
        $validated = $request->validate([
            'address_id' => 'required|exists:addresses,id',
        ]);

        /** @var \App\Models\User|\Laravel\Sanctum\HasApiTokens $user */
        $user = $request->user();

        if (!$user) {
            return response()->json(['message' => 'غير مصرح'], 401);
        }

        $address = $user->addresses()->where('id', $validated['address_id'])->first();

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

        $address->delete();

        return response()->json(['message' => 'تم حذف العنوان بنجاح']);
    }

    /**
     * تحديث عنوان
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateAddress(Request $request)
    {
        // التحقق من البيانات المدخلة
        $validated = $request->validate([
            'address_id' => 'required|exists:addresses,id',
            'address_line_1' => 'required|string|max:255',
            'address_line_2' => 'nullable|string|max:255',
            'city' => 'required|string|max:100',
            'country' => 'required|string|max:100',
            'postal_code' => 'nullable|string|max:20',
            'is_default' => 'boolean',
            'whatsapp' => 'nullable|string|max:20',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|string|max:20',
            'name' => 'nullable|string|max:20',
        ]);

        /** @var \App\Models\User|\Laravel\Sanctum\HasApiTokens $user */
        $user = $request->user();

        if (!$user) {
            return response()->json(['message' => 'غير مصرح'], 401);
        }

        $address = $user->addresses()->where('id', $validated['address_id'])->first();

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

        if ($validated['is_default'] ?? false) {
            $user->addresses()->update(['is_default' => false]);
        }

        $address->update([
            'address_line_1' => $validated['address_line_1'],
            'address_line_2' => $validated['address_line_2'],
            'city' => $validated['city'],
            'country' => $validated['country'],
            'postal_code' => $validated['postal_code'],
            'is_default' => $validated['is_default'] ?? false,
            'whatsapp' => $validated['whatsapp'] ?? false,
            'email' => $validated['email'] ?? false,
            'phone' => $validated['phone'] ?? false,
            'name' => $validated['name'] ?? false,

        ]);

        return response()->json([
            'message' => 'تم تحديث العنوان بنجاح',
            'address' => $address,
        ]);
    }
}
