<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Validator;
use Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models;
use App\ActivityLog;
use App\Libs\Smsgateway;

class ApiDealersController extends Controller
{
    public function handleLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Email and password are required.',
                'errors' => $validator->errors()
            ], 422);
        }

        $org_user = Models\OrgUser::where('email', $request->email)->first();
        
        if (!$org_user || !Hash::check($request->password, $org_user->password)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Email or password incorrect.'
            ], 401);
        }



        $desc = [
            'title' => 'Login',
            'data' => $org_user->name . ' Successful login'
        ];

        $activity = new ActivityLog();
        $activity->user_id = $org_user->id;
        $activity->user_type = 'organisation';
        $activity->description = json_encode($desc);
        $activity->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Login successful.',
            'data' => [
                'user' => $org_user,
            ]
        ]);
    }
    public function getBalance(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'dealer_id' => 'required|integer|exists:org_users,id'
        ]);

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

        $dealer_id = $request->dealer_id;

        $org_user = Models\OrgUser::find($dealer_id);
        
        if (!$org_user || !Hash::check($request->password, $org_user->password)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Email or password incorrect.'
            ], 401);
        }
        $desc = [
            'title' => 'Login',
            'data' => $org_user->name . ' Successful login'
        ];

        $activity = new ActivityLog();
        $activity->user_id = $org_user->id;
        $activity->user_type = 'organisation';
        $activity->description = json_encode($desc);
        $activity->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Balance check successful',
            'data' => [
                'balance' => $org_user->balance,
            ]
        ]);
    }
    public function getTransactionsJson(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'dealer_id' => 'required|integer|exists:org_users,id'
        ]);

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

        $dealer_id = $request->dealer_id;
        
        $query = DB::table('merchant_top_ups')
            ->join('org_users', 'merchant_top_ups.org_user_id', '=', 'org_users.id')
            ->join('merchants', 'merchant_top_ups.merchant_id', '=', 'merchants.id')
            ->select('merchant_top_ups.id', 'merchant_top_ups.status', 'merchants.phone', 'merchants.fullname', 'merchant_top_ups.payment_method', 'merchant_top_ups.org_user_id', 'merchant_top_ups.amount', 'merchant_top_ups.created_at')
            ->where('merchant_top_ups.org_user_id', $dealer_id);

        if ($request->has('keyword')) {
            $keyword = $request->keyword;
            $query->where(function($q) use ($keyword) {
                $q->where('merchants.fullname', 'LIKE', "%{$keyword}%")
                  ->orWhere('merchants.phone', 'LIKE', "%{$keyword}%")
                  ->orWhere('merchant_top_ups.status', 'LIKE', "%{$keyword}%")
                  ->orWhere('merchant_top_ups.payment_method', 'LIKE', "%{$keyword}%")
                  ->orWhere('merchant_top_ups.amount', 'LIKE', "%{$keyword}%")
                  ->orWhere('merchant_top_ups.created_at', 'LIKE', "%{$keyword}%");
            });
        }

        $transactions_arr = $query->orderBy('merchant_top_ups.created_at', 'DESC')->paginate(10);

        return response()->json([
            'status' => 'success',
            'data' => $transactions_arr
        ]);
    }

    public function getMyTopUpsJson(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'dealer_id' => 'required|integer|exists:org_users,id'
        ]);
        

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

        $dealer_id = $request->dealer_id;
        
        $query = DB::table('organisation_top_ups')
            ->join('org_users', 'organisation_top_ups.org_id', '=', 'org_users.org_id')
            ->join('users', 'organisation_top_ups.user_id', '=', 'users.id')
            ->select('organisation_top_ups.id', 'organisation_top_ups.status', 'org_users.phone', 'users.name', 'organisation_top_ups.payment_method', 'organisation_top_ups.org_id', 'organisation_top_ups.amount', 'organisation_top_ups.created_at')
            ->where('organisation_top_ups.org_user_id', $dealer_id);

        if ($request->has('keyword')) {
            $keyword = $request->keyword;
            $query->where(function($q) use ($keyword) {
                $q->where('org_users.name', 'LIKE', "%{$keyword}%")
                  ->orWhere('org_users.phone', 'LIKE', "%{$keyword}%")
                  ->orWhere('organisation_top_ups.status', 'LIKE', "%{$keyword}%")
                  ->orWhere('organisation_top_ups.payment_method', 'LIKE', "%{$keyword}%")
                  ->orWhere('organisation_top_ups.amount', 'LIKE', "%{$keyword}%")
                  ->orWhere('organisation_top_ups.created_at', 'LIKE', "%{$keyword}%");
            });
        }

        $transactions_arr = $query->orderBy('organisation_top_ups.created_at', 'DESC')->paginate(10);

        return response()->json([
            'status' => 'success',
            'data' => $transactions_arr
        ]);
    }

    public function merchantTopupStore(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 getActivity(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'dealer_id' => 'required|integer|exists:org_users,id'
        ]);
        

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

        $dealer_id = $request->dealer_id;
        
        $activities = ActivityLog::with('admin')
            ->where('user_type', 'organisation')
            ->where('user_id', $dealer_id)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return response()->json([
            'status' => 'success',
            'data' => $activities
        ]);
    }
}

///http://206.225.87.174:8131/dealer/topupmerchant
