<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\Merchant;
use App\Models\Transaction;
use App\ActivityLog;
use App\Libs\Smsgateway;


class DealerAoiController extends Controller
{
  

    public function merchantTopupStoreOld(Request $request){
        $validator = Validator::make($request->all(), [
            'merchant_id' => 'required|integer|exists:merchants,id',
            'amount'   => 'required|numeric|min:1',
            'dealer_id' => 'required|integer|exists:org_users,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 3,
                'status' => 'failed',
                'message' => 'Validation error.',
                'errors' => $validator->errors()
            ], 422);
        }


        $dealer_id = $request->dealer_id;
        $merchant_id = $request->merchant_id;

        $amount = (float) $request->amount;

        $dealer = Models\OrgUser::findOrFail($dealer_id);
        $merchant = Models\Merchant::findOrFail($merchant_id);

        if ($amount > $dealer->balance) {
            return response()->json([
                'code' => 3,
                'status' => 'failed',
                'message' => 'Insufficient Balance.', 
                'balance' => $dealer->balance
            ], 400);
        }

        DB::beginTransaction();

        try {
            Models\MerchantTopUp::create([
                'merchant_id'      => $merchant_id,
                'amount'           => $amount,
                'transaction_id'   => 'MCH-' . Str::uuid(),
                'org_user_id'      => $dealer_id,
                'created_by'       => $dealer_id,
                'payment_method'   => 'cash'
            ]);
            
            $merchant->increment('balance', $amount);
            $dealer->decrement('balance', $amount);

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error($e);

            return response()->json([
                'code' => 3,
                'status' => 'failed',
                'message' => 'Merchant Top Up failed.'
            ], 500);
        }

        ActivityLog::create([
            'user_id' => $dealer_id,
            'user_type' => 'Dealer',
            'description' => json_encode([
                'title' => 'Dealer to Merchant Top Up',
                'data'  => 'MWK ' . number_format($amount, 2) . ' for ' . $merchant->fullname,
                'type'  => 'dealer topup'
            ])
        ]);

        $merchant->refresh();

        try {
            if (!app()->environment('local')) {
                (new Smsgateway())->sendSmsNew(
                    $merchant->phone,
                    "Hello {$merchant->fullname}, your account has been credited with MWK {$amount}. Your new balance is MWK {$merchant->balance}."
                );
            }
        } catch (\Exception $e) {
            \Log::error($e);
        }
        
        return response()->json([
            'code' => 1,
            'status' => 'success',
            'message' => 'Merchant Top Up Successfully completed.'
        ]);
    }

    public function merchantTopupStore(Request $request){
        return response()->json([
            'code' => 1,
            'status' => 'success',
            'request' => $request->all(),
            'message' => 'Merchant Top Up Successfully completed.'
        ]);
    }
}
