<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Order;
use App\Models\Service;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Models\AdminNotification;
use Illuminate\Support\Facades\Validator;


class ApiController extends Controller
{
    public function process(Request $request)
    {

        if (!$request->action) {
            return response()->json(["error" => "The action field is required"]);
        }

        if (!$request->key) {
            return response()->json(["error" => "The api key field is required"]);
        }

        $actionExists = array('services', 'add', 'status', 'refill', 'refill_status', 'balance');

        if (!in_array($request->action, $actionExists)) {
            return response()->json(["error" => "Invalid action"]);
        }

        //Checking api key exist
        $user = User::where('api_key', $request->key)->first();

        if (!$user) {
            return response()->json(['error' => 'Invalid api key']);
        }

        if ($user->status == 0) {
            return response()->json(['error' => 'This credential is no longer']);
        }

        if(strtolower($request->action) == 'services') {

            $services  = Service::where('status',1)->with('category')->get();
            $modifyService = [];

            foreach($services as $service) {
                $modifyService[] = [
                    "service"  => $service->id,
                    "name"     => $service->name,
                    "rate"     => $service->price,
                    "min"      => $service->min,
                    "max"      => $service->max,
                    "category" => @$service->category->name,
                ];
            }

            return response()->json($modifyService);

        }elseif(strtolower($request->action) == 'add') {

            //Service
                $service = Service::where('status',1)->find($request->service);

                if(!$service) {
                    return response()->json(['error' => 'Invalid Service Id']);
                }

                if (!$request->link) {
                    return response()->json(['error' => 'The link field is required']);
                }

                if(!$request->quantity) {
                    return response()->json(['error' => 'The quantity field is required']);
                }

                $quantity = $request->quantity;
                if ($service->drip_feed == 1) {
                    $rules['runs'] = 'required|integer|not_in:0';
                    $rules['interval'] = 'required|integer|not_in:0';
                    $validator = Validator::make($request, $rules);
                    if ($validator->fails()) {
                        return response()->json(['errors' => $validator->errors()], 422);
                    }
                    $quantity = $request->quantity * $request->quantity->runs;
                }

                if ($quantity < $service->min && $quantity > $service->max) {
                    return response()->json(['error' => 'Please follow the limit']);
                }

                $price =  $price = round(($quantity * $service->price) / 1000, 2);
                //Subtract user balance
                $user = User::where('api_key', $request->key)->firstOrFail();

                if ($user->balance < $price) {
                    return response()->json(['error' => 'Insufficient balance']);
                }

                //Save order record
                $order              = new Order();
                $order->order_no    = getTrx(4);
                $order->user_id     = $user->id;
                $order->category_id = $service->category_id;
                $order->service_id  = $service->id;
                $order->link        = $request->link;
                $order->quantity    = $request->quantity;
                $order->runs        = $request->runs ?? 0;
                $order->interval    = $request->interval ?? 0;
                $order->price       = $price;
                $order->remains      = $request->quantity;

                $order->save();
                $user->balance -= $price;
                $user->save();

                //Create Transaction
                $transaction               = new Transaction();
                $transaction->user_id      = $user->id;
                $transaction->amount       = $price;
                $transaction->post_balance = getAmount($user->balance);
                $transaction->trx_type     = '-';
                $transaction->details      = 'Order for ' . $service->name;
                $transaction->trx          = getTrx();
                $transaction->save();

                //Create admin notification
                $adminNotification            = new AdminNotification();
                $adminNotification->user_id   = $user->id;
                $adminNotification->title     = 'New order request for ' . $service->name;
                $adminNotification->click_url = urlPath('admin.order.edit', $order->id);
                $adminNotification->save();

                notify($user, 'PENDING_ORDER', [
                    'service_name'  => @$order->service->name,
                    'username' => @$user->username,
                    'price' => $order->price,
                ]);

                return response()->json(['order' => $order->id]);

        }elseif(strtolower($request->action) == 'status'){

            if(!$request->order) {
                return response()->json(["error" => "The order field is required"]);
            }

            //Service
            $order = Order::where('id', $request->order)->select(['status', 'start_count', 'remains'])->first();

            if(!$order) {
                return response()->json(['error' => 'Invalid Order Id']);
            }

            $order['status'] = ($order->status == 0 ? 'pending' : ($order->status == 1 ? 'processing' : ($order->status == 2 ? 'completed' : ($order->status == 3 ? 'cancelled' : 'refunded'))));

            $order['currency'] = gs()->cur_text;

            return response()->json($order);

        }elseif(strtolower($request->action) == 'balance'){

            $balance = User::where('api_key', $request->key)->select(['balance'])->first();

            if (!$balance) {
                return response()->json(['error' => 'Invalid api key']);
            }

            $balance = [
                "balance" => showAmount($balance->balance),
                "currency" => gs()->cur_text,
            ];

            return response()->json($balance);

        }else{
            return response()->json(["error" => "The action are not available"]);
        }

    }

}
