<?php

namespace App\Http\Controllers;

use App\Models\Employe;
use App\Models\_Subscriptions;
use App\Models\Users;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class Users_ extends Controller
{
    public function index()
    {
        $users = Users::orderBy('cust_id', 'DESC')->fastPaginate();
        return view('users.active-user', compact('users'));
    }

    public function BanIndex()
    {
        $users = Users::where('status',1)->orderBy('inserted_at', 'DESC')->paginate(15);
        return view('users.banned-user', compact('users'));
    }
    
    public function AccountDeleteRequestIndex()
    {
        $data = DB::table('delete_account')->orderBy('id', 'DESC')->paginate(15);
        return view('users.deleted-account', compact('data'));
    }

    public function TopIndex()
    {
        $users = Users::orderBy('balance', 'DESC')->fastPaginate();

        return view('users.top-user', compact('users'));
    }

    public function searchQuery($query)
    {
        if ($query == "null") {
            $users = [];
            $query = '';
        } else {
            $query=trim($query);
            $users =DB::table('customer')->where('name','like','%'.$query.'%')
                ->orWhere('email', 'like', '%'.$query.'%')
                ->orWhere('country', 'like', '%'.$query.'%')
                ->orWhere('refferal_id', '=', $query)
                ->orWhere('ip', 'like', $query)
                ->orWhere('cust_id', '=', $query)->
                    paginate();
          
        }

        return view('users/search', ['users' => $users, 'query' => $query]);
    }

    public function removeUser($id)
    {
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        try {
            DB::table('customer')->where('cust_id', $id)->delete();
            DB::table('transaction')->where('user_id', $id)->delete();
            DB::table('recharge_request')->where('user_id', $id)->delete();
            DB::table('data_dailyoffer')->where('user_id', $id)->delete();
            DB::table('monitor_report')->where('userid', $id)->delete();
            DB::table('scratch_card')->where('user_id', $id)->delete();
            DB::table('task_count')->where('user_id', $id)->delete();
            DB::table('tbl_noti')->where('user_id', $id)->delete();
            DB::table('tbl_support')->where('user_id', $id)->delete();
            return 1;
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['msgError' => 'cannot be deleted.']);
        }
    }
    
    public function removeTransaction($id){
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        DB::table('transaction')->where('user_id', $id)->delete();
        return redirect('/user-track/' . $id)->with('success', 'History Cleared');
    }
    
    public function getUserSubscription($id){
        
      $sub= _Subscriptions::get();
      $user=Users::find($id);
      $currentSub=_Subscriptions::where('id',$user->subscription)->get();

      return view('users/user-upgrade',['data'=>$user,'sub'=>$sub,'current'=>$currentSub]);
        
    }
    
    public function getSubscribedUser($filter){
        switch($filter){
            case "active":
                     $users = DB::table('customer')->
                        join('subscriptions','customer.subscription','=','subscriptions.id')
                        ->select('customer.name','customer.email','customer.country','customer.subscription','customer.cust_id','customer.profile','customer.type','customer.purchased_at','customer.expired_at','subscriptions.title','subscriptions.amount','subscriptions.currency')
                         ->where('customer.subscription','>',1)
                        ->orderBy('cust_id','DESC')->paginate();
    
                break;
                
            case "expired":
                   $users = DB::table('customer')->
                        join('subscriptions','customer.expire_sub','=','subscriptions.id')
                        ->select('customer.name','customer.email','customer.country','customer.subscription','customer.cust_id','customer.profile','customer.type','customer.purchased_at','customer.expired_at','subscriptions.title','subscriptions.amount','subscriptions.currency')
                        ->where('customer.expire_sub','>',1)
                        ->where('customer.expired_at','<',date('Y-m-d'))
                        ->orderBy('customer.expired_at','DESC')->paginate();
                        
                break;    
            
        }
        
        return view('users.subscribed-user',['users'=>$users,'sub'=>_Subscriptions::select('title','id','amount','currency','valid_for')->get()]);
    }
    
    public function updateUserSubscription(Request $req){
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }    
        $subid=$req->subscription;
        $user=Users::find($req->id);
        
        if($subid==$user->subscription){
            return back()->withErrors(['msgError' => 'User Current Plan and Selected plan are Same.']);
        }
        
        $subs=_Subscriptions::find($subid);
        
        $day=$subs->valid_for*30;
        $currentTime=Carbon::now();
        $expiredAt=Date('Y-m-d', strtotime('+'.$day.' days'));
        
        $promo=false;
        if($subs->promo_coin>0){
            $promo=true;
            $oldcoin=$user->promo_balance;
            $total=$oldcoin+$subs->promo_coin;
            $user->promo_balance=$total;
        }
    
        // updating user
        $user->purchased_at=$currentTime;
        $user->expired_at=$expiredAt;
        $user->subscription=$subid;
        $user->expire_sub=$subid;
        $user->save();
        
        //insertsub
        $insertRecord=DB::table('subscribed_user')->insert([
            'user_id'=>$user->cust_id,
            'sub_id'=>$subid,
            'validity'=>$subs->valid_for,
            'days'=>$day,
            'subscribed_at'=>$currentTime,
            'expired_at'=>$expiredAt,
            'amount'=>$subs->amount,
            'sub_info'=>$subs->title,
            'payment_mode'=>'Admin Approved',
            'remark'=>'Upgraded by Admin'
            ]);
         
        if($promo){
             DB::table('transaction')
                ->insert([
                    'tran_type' => 'credit',
                    'user_id' => $req->id,
                    'amount' => $subs->promo_coin,
                    'type' => 'Promo Coin',
                    'remained_balance' => $total,
                    'inserted_at' => Carbon::now(),
                    'remarks' =>'Subscription Promo Coin Credit'
                ]);
        }
        
        return redirect('/users/search/null')->with('success','Account Upgrade Successfully !');
    }
    
    public function updateStatus(Request $request){
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }
       $user = Users::find($request->id);
       if($user->status==0){
           $status=1;
           $type='Acctoun Ban';
       }else{
            $status=0;
            $type='Ban Removed';
       }
       
       $user->status=$status; 
       $user->reason=$request->reason; 
       $user->banned_time=Carbon::now(); 
       $res= $user->save();
       DB::table('monitor_report')->insert(['userid' => $request->id, 'type' =>$type,'remark'=>$request->reason]);

        return redirect('/users/banned')->with('success','Account Status Updated !');
          
    }

    public function updateCoin(Request $req)
    {
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }
        $user = Users::find($req->id);
        $coin = $req->coin;

        if ($req->type == 'debit') {
            if ($user->balance >= $coin) {
                  $total = $user->balance - $coin;
                    $user->balance = $total;
            }else{
                return back()->withErrors(['msgError' => 'Not Enough Coin in Wallet to Deduct.']);
            }
          
        } else {
            $total = $user->balance + $coin;
            $user->balance = $total;
        }

        $res = $user->save();
        if ($res) {
            DB::table('transaction')
                ->insert([
                    'tran_type' => $req->type,
                    'user_id' => $req->id,
                    'amount' => $coin,
                    'type' => 'Coin ' . $req->type,
                    'remained_balance' => $total,
                    'inserted_at' => Carbon::now(),
                    'remarks' => $req->remark
                ]);
            return redirect('/user-track/' . $req->id)->with('success', 'User Wallet Updated');
        } else {
              return back()->withErrors(['msgError' => 'Technical Error.']);
        }
    }
}
