<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coin_Package;
use App\Models\Coin_Package_Transaction;
use App\Models\User;
use App\Models\Common;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class CoinTransactionController extends Controller
{
    private $folder = "user";
    public $common;
    public function __construct()
    {
        $this->common = new Common;
    }

    public function index(Request $request)
    {
        try {

            $params['data'] = [];
            if ($request->ajax()) {

                $input_search = $request['input_search'];
                $input_type = $request['input_type'];

                $query = Coin_Package_Transaction::query();

                if (!empty($input_search)) {
                    $query->where('transaction_id', 'LIKE', "%{$input_search}%");
                }

                if ($input_type == "today") {
                    $query->whereDay('created_at', date('d'))->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'));
                } elseif ($input_type == "month") {
                    $query->whereMonth('created_at', date('m'))->whereYear('created_at', date('Y'));
                } elseif ($input_type == "year") {
                    $query->whereYear('created_at', date('Y'));
                }

                $data = $query->with('coin_package', 'user')->latest()->get();
               
                for ($i = 0; $i < count($data); $i++) {
                    if ($data[$i]['user'] != null) {

                        $this->common->imageNameToUrl(array($data[$i]['user']), 'image', $this->folder);
                        $data[$i]['date'] = date("Y-m-d", strtotime($data[$i]['created_at']));
                    }
                }

                return DataTables()::of($data)
                    ->addColumn('action', function ($row) {

                        $coin_transaction_delete = __('Label.delete_coin_transaction');

                        $delete = '<form onsubmit="return confirm(\'' . $coin_transaction_delete . '\');" method="POST" action="' . route('coin_transaction.destroy', [$row->id]) . '">
                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                        <input type="hidden" name="_method" value="DELETE">
                        <button type="submit" class="edit-delete-btn" style="outline: none;"><i class="fa-solid fa-trash-can fa-xl"></i></button></form>';

                        $btn = '<div class="d-flex justify-content-around">';
                        $btn .= $delete;
                        $btn .= '</div>';
                        return $btn;
                    })
                    ->addIndexColumn()                    
                    ->make(true);
            }
            return view('admin.coin_transaction.index', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function create(Request $request)
    {
        try {
            $params['data'] = [];
            $params['user'] = User::where('id', $request->user_id)->first();
            $params['package'] = Coin_Package::get();

            return view('admin.coin_transaction.add', $params);
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function searchUser(Request $request)
    {
        try {
            $name = $request->name;
            $user = User::orWhere('full_name', 'like', '%' . $name . '%')->orWhere('mobile_number', 'like', '%' . $name . '%')->orWhere('email', 'like', '%' . $name . '%')->latest()->get();

            $url = url('admin/coin_transaction/create?user_id');
            $text = "<table width='100%' class='table table-striped category-table text-center table-bordered'><tr style='background: #F9FAFF;'><th>" . __('Label.Full_Name') . "</th><th>" . __('Label.Mobile') . "</th><th>" . __('Label.Email') . "</th><th>" . __('Label.Action') . "</th></tr>";
            if ($user->count() > 0) {
                foreach ($user as $row) {

                    $a = '<a class="btn-link" href="' . $url . '=' . $row->id . '">' . __('Label.select') . '</a>';
                    $text .= '<tr><td>' . $row->full_name . '</td><td>' . $row->mobile_number . '</td><td>' . $row->email . '</td><td>' . $a . '</td></tr>';
                }
            } else {
                $text .= '<tr><td colspan="4">User Not Found</td></tr>';
            }
            $text .= '</table>';

            return response()->json(array('status' => 200, 'success' => 'Search User', 'result' => $text));
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id' => 'required',
                'coin_package_id' => 'required'
            ]);
            if ($validator->fails()) {
                $errs = $validator->errors()->all();
                return response()->json(array('status' => 400, 'errors' => $errs));
            }

            $package = Coin_Package::where('id', $request->coin_package_id)->first();

            $Transction = new Coin_Package_Transaction();
            $Transction->user_id = $request->user_id;
            $Transction->coin_package_id = $request->coin_package_id;
            $Transction->price = $package->price;
            $Transction->coin = $package->coin;
            $Transction->transaction_id = 'admin';
            $Transction->description = 'admin';
            $Transction->status = 1;

            if ($Transction->save()) {
                if ($Transction->id) {

                    $user = User::where('id', $Transction->user_id)->first();
                    if ($user != null) {

                        $user->update(['coin_wallet' => $Transction->coin]);
                    }

                    return response()->json(array('status' => 200, 'success' => __('Label.Transction_Add_Successfully')));
                } else {
                    return response()->json(array('status' => 400, 'errors' => __('Label.Transction_Not_Add')));
                }
            } else {
                return response()->json(array('status' => 400, 'errors' => __('Label.Transction_Not_Add')));
            }
        } catch (Exception $e) {
            return response()->json(array('status' => 400, 'errors' => $e->getMessage()));
        }
    }
    public function destroy($id)
    {
        try {

            Coin_Package_Transaction::where('id', $id)->delete();
            return redirect()->route('coin_transaction.index')->with('success', __('Label.data_delete_successfully'));
        } catch (Exception $e) {
            return response()->json(['status' => 400, 'errors' => $e->getMessage()]);
        }
    }
}
