<?php

namespace App\Http\Controllers\Subscriptions;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\CustomerBalance;
use App\Models\ReceiptVoucher;
use App\Models\Settings\RegionalSettings\Nationality;
use App\Models\Subscription;
use App\Models\SubscriptionTransfer;

use App\Traits\Basics\HandlesJsonExceptions;
use App\Traits\Basics\HasCrudActions;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

use Exception;
use Throwable;

class SubscriptionTransferController extends Controller
{
    use HasCrudActions, HandlesJsonExceptions;

    /** ==============* Properties *============== */
    protected string $model = SubscriptionTransfer::class;
    protected string $viewPath = 'subscriptions.transfers.';

    public function store(Request $request): ?JsonResponse
    {
        $request->validate([
            'new_customer_id' => 'required|exists:customers,id',
            'transfer_reason' => 'nullable|string|max:500',
        ]);

        $id = $request->input('id');
        $subscription = Subscription::query()->find($id);

        if (!$subscription) {
            return response()->json([
                'error'   => true,
                'message' => __('messages.not_found')
            ]);
        }

        if ($subscription->customer_id == $request->new_customer_id) {
            return response()->json([
                'error'   => true,
                'message' => __('You must select a different client')
            ]);
        }

        if ($subscription->status !== 'active') {
            return response()->json([
                'error'   => true,
                'message' => __('The subscription cannot be transferred because it is inactive.')
            ]);
        }

        try {
            DB::beginTransaction();
            $customer = Customer::query()->find($request->new_customer_id);

            $nationality = Nationality::findOrFail($customer->nationality_id);
            $isSaudi = $nationality->id == 1;
            $enable_tax_on_saudis = settings('enable_tax_on_saudis') == 1;
            $enable_tax = settings('enable_tax') == 1;

            if ($isSaudi) {
                $vatRate = $enable_tax_on_saudis ? $subscription->vat : 0;
            } else {
                $vatRate = $enable_tax ? (float) $subscription->vat : 0;
            }

            $amount         = $subscription->price;
            $discount       = $subscription->discount;
            $netAmount      = $amount - $discount;
            $vatValue       = ($netAmount * $vatRate) / 100;
            $total          = $netAmount + $vatValue;
            $amountPaid     = $subscription->amount_paid ?? 0;
            $remainingPaid  = $total - $amountPaid;

            $subscription->transferToCustomer(
                $request->new_customer_id,
                $request->transfer_reason,
            );

            $subscription->update([
                'amount'                => $amount,
                'discount'              => $discount,
                'net_amount'            => $netAmount,
                'vat'                   => $vatRate,
                'vat_value'             => $vatValue,
                'total'                 => $total,
                'amount_paid'           => $amountPaid,
                'remaining_paid'        => $remainingPaid,
            ]);

            $voucher = ReceiptVoucher::create([
                'customer_id' => $request->new_customer_id,
                'subscription_id' => $subscription->id,
                'payment_method_id' => $subscription->payment_method_id,
                'amount' => $subscription->amount_paid,
                'payment_date' => $subscription->start_date,
                'type' => 'subscription',
                'reference_number' => $subscription->reference_number,
                'notes' => 'سند قبض خاص بإشتراك محول رقم: ' . $subscription->code,
                'status' => 'active',
                'created_by' => Auth::id(),
            ]);

            $walletDisabled = settings("activate_wallet") == 0;
            if (!$walletDisabled) {
                $oldCustomerBalance = CustomerBalance::getOrCreateForCustomer($subscription->customer_id);
                $newCustomerBalance = CustomerBalance::getOrCreateForCustomer($request->new_customer_id);

                // رجّع الفلوس اللي كان دفعها
                if ($subscription->amount_paid > 0) {
                    $oldCustomerBalance->updateBalance(
                        $subscription->amount_paid,
                        'refund',
                        $voucher->id,
                        'تحويل اشتراك - استرداد',
                        Auth::id()
                    );
                }

                // شيل المديونية (عكسها)
                if ($subscription->remaining_paid > 0) {
                    $oldCustomerBalance->updateBalance(
                        $subscription->remaining_paid,
                        'deposit',
                        $voucher->id,
                        'إلغاء مديونية بسبب تحويل',
                        Auth::id()
                    );
                }

                // ياخد الفلوس
                if ($subscription->amount_paid > 0) {
                    $newCustomerBalance->updateBalance(
                        $subscription->amount_paid,
                        'deposit',
                        $voucher->id,
                        'رصيد اشتراك محول',
                        Auth::id()
                    );
                }

                // يتحمل الدين
                if ($subscription->remaining_paid > 0) {
                    $newCustomerBalance->updateBalance(
                        $subscription->remaining_paid,
                        'debit',
                        $voucher->id,
                        'مديونية اشتراك محول',
                        Auth::id()
                    );
                }
            }

            DB::commit();

            return response()->json([
                "success" => true,
                "message" => __("messages.success_transferring_subscription")
            ]);

        } catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'error'   => true,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function history(Subscription $subscription)
    {
        $transfers = $subscription->transfers()
            ->with(['fromCustomer', 'toCustomer', 'transferredByUser'])
            ->latest()
            ->get();

        return view('subscriptions.transfer-history', compact('subscription', 'transfers'));
    }

    public function rollback(SubscriptionTransfer $transfer): ?RedirectResponse
    {
        // التحقق من صلاحية المستخدم (يجب أن يكون مدير)
        if (!auth()->user()->hasRole('admin')) {
            return back()->with('error', 'ليس لديك صلاحية إلغاء التحويل');
        }

        try {
            DB::beginTransaction();

            $subscription = $transfer->subscription;

            // إعادة الاشتراك للعميل الأصلي
            $subscription->update([
                'customer_id' => $transfer->from_customer_id,
                'transferred_from_customer_id' => null,
                'transferred_to_customer_id' => null,
                'transferred_by' => null,
                'transferred_at' => null,
                'transfer_reason' => null,
                'is_transferred' => false,
            ]);

            ReceiptVoucher::where('subscription_id', $subscription->id)
                ->update(['customer_id' => $transfer->from_customer_id]);

            $transfer->delete();

            DB::commit();

            return redirect()->route('subscriptions.show', $subscription)
                ->with('success', 'تم إلغاء التحويل بنجاح');

        } catch (Exception $e) {
            DB::rollBack();
            return back()->with('error', 'حدث خطأ أثناء إلغاء التحويل: ' . $e->getMessage());
        }
    }


}
