<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\AccountTransaction;
use App\Models\BusinessSetting;
use App\Models\DeliveryMan;
use App\Models\DMLog;
use App\Models\DMMonthlySubscription;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class DMMonthlySubscriptionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request): \Illuminate\Http\JsonResponse
    {
        $DMMonthlySubscriptionAmount = BusinessSetting::where('key', 'd_m_monthly_subscription_amount')->first();
        if(!$DMMonthlySubscriptionAmount or $DMMonthlySubscriptionAmount->value == 0){
            return response()->json(['message' => 'لم يتم تفعيل الاشتراكات بعد!'], 405);
        }

        if(!isset($request->delivery_man_id)){
            return response()->json(['message' => 'حقل delivery_man_id مطلوب!'], 406);
        }

        $deliveryManId = $request->delivery_man_id;
        $amount = $DMMonthlySubscriptionAmount->value;
        $now = Carbon::now();
        $afterMonth = (clone $now)->addMonthNoOverflow();

        if(DeliveryMan::isHaveActiveMonthlySubscription($deliveryManId)){
            return response()->json(['message' => 'لديك اشتراك فعال!'], 408);
        }

        $dm = DeliveryMan::where('id', $deliveryManId)->first();

        if(!$dm or $dm->status == 0 or $dm->earning != '1'){
            return response()->json(['message' => 'لا يمكنك الاشتراك بهذه الخدمة!'], 403);
        }

        $currentBalance = DeliveryMan::getTheRemainingBalanceForDeliveryMan($dm, '', '') * -1;

        if($currentBalance < $amount){
            return response()->json(['message' => 'لا يوجد لديك رصيد كافي للإشتراك الشهري!'], 407);
        }

        try {
            // ملاحظة: إذا بدك معلومات الاسم والرقم من الـ request، مرّرها. هون رح نستخدم بيانات الـ $dm كقيمة افتراضية
            $payload = [
                'f_name'        => $dm->f_name,
                'l_name'        => $dm->l_name,
                'phone'         => $dm->phone,
                'payment_value' => $amount,
                'note'          => sprintf('اشتراك شهري من %s إلى %s (dm_id:%d)', $now->toDateString(), $afterMonth->toDateString(), $deliveryManId),
                // معلومات مرجعية إضافية:
                'ref'           => 'اشتراك شهري للمندوب ' . $dm->f_name . ' ' . $dm->l_name . ' من تاريخ ' . $now->toDateString() . ' الى ' . $afterMonth->toDateString(),
                'delivery_man_id' => $deliveryManId,
            ];

            $http = Http::timeout(10)
                ->retry(2, 300) // محاولتين، انتظار 300ms
                ->acceptJson()
                ->withHeaders([
                    'Content-Type' => 'application/json',
                ]);

            $b2bResponse = $http->post('https://postajji.net/b2b/api/subscriptions/charge', $payload);

            if (!$b2bResponse->ok()) {
                Log::warning('B2B charge non-200', ['status' => $b2bResponse->status(), 'body' => $b2bResponse->body()]);
                return response()->json('تعذّر تنفيذ العملية مع نظام الأمين. حاول لاحقاً.', 502);
            }

            $b2bJson = $b2bResponse->json();
            if (!data_get($b2bJson, 'success')) {
                Log::warning('B2B charge returned failure', ['json' => $b2bJson]);
                return response()->json(['message' => 'فشل تنفيذ العملية في نظام الأمين.'], 502);
            }

            // ممكن تحتاج الرقم للّوغ أو الربط
            $alameenNumber = data_get($b2bJson, 'data.alameen_number');

        } catch (\Throwable $e) {
            Log::error('B2B charge exception', ['e' => $e]);
            return response()->json(['message' => 'خطأ في الاتصال مع خدمة B2B. حاول لاحقاً.'], 502);
        }

        try {
            DB::beginTransaction();

            $account_transaction = new AccountTransaction();
            $account_transaction->from_type = 'deliveryman';
            $account_transaction->from_id = $deliveryManId;
            $account_transaction->method = 'تلقائية';
            $account_transaction->ref = 'اشتراك شهري من تاريخ ' .  $now . ' الى ' .$afterMonth;
            $account_transaction->amount = $amount * -1;
            $account_transaction->current_balance = $currentBalance * -1;
            $account_transaction->transaction_date = $now;
            $account_transaction->admin_id = null;
            $account_transaction->save();

            if(!empty($request->dm_log_message)) {
                $getDMLogMessage = 'اشتراك شهري من تاريخ ' .  $now . ' الى ' . $afterMonth;
                DMLog::createLog($deliveryManId, $getDMLogMessage, $amount, null);
            }

            DMMonthlySubscription::create([
                'delivery_man_id' => $deliveryManId,
                'amount' => $amount,
                'start_at' => $now,
                'end_at' => $afterMonth,
            ]);

            DB::commit();
            return response()->json(['message' => 'تم الاشتراك بنجاح.'], 200);

        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error('Store subscription transaction failed after B2B charge', ['e' => $e]);
            return response()->json(['message' => 'حدث خطأ أثناء تثبيت الاشتراك داخلياً. لم يتم الخصم.'], 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\DMMonthlySubscription  $dMMonthlySubscription
     * @return \Illuminate\Http\Response
     */
    public function show(DMMonthlySubscription $dMMonthlySubscription)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\DMMonthlySubscription  $dMMonthlySubscription
     * @return \Illuminate\Http\Response
     */
    public function edit(DMMonthlySubscription $dMMonthlySubscription)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\DMMonthlySubscription  $dMMonthlySubscription
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, DMMonthlySubscription $dMMonthlySubscription)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\DMMonthlySubscription  $dMMonthlySubscription
     * @return \Illuminate\Http\Response
     */
    public function destroy(DMMonthlySubscription $dMMonthlySubscription)
    {
        //
    }
}
