<?php

namespace App\Http\Controllers;

use App\Models\Users;
use App\Models\_Subscriptions;
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 App\Http\Controllers\Fun;
use Carbon\Carbon;

class Subscriptions extends Controller
{
    public function index()
    {
        $data = _Subscriptions::orderBy('id', 'DESC')->paginate();
        return view('subscriptions.index', compact('data'));
    }
    
    public function create ()
    {
        return view('subscriptions.add');
    }
    
    public function edit(_Subscriptions $id)
    {
        return view('subscriptions.edit',['data'=>$id]);
    }
    
    public function subReport(){
      $data = DB::table('subscribed_user')->
            join('customer','customer.cust_id','=','subscribed_user.user_id')
            ->select('customer.name','customer.email','customer.country','customer.cust_id','subscribed_user.*')
            ->orderBy('subscribed_user.id','DESC')->paginate();
            
        return view('subscriptions/sub-transaction',['data'=>$data]);
    }
    
        
    public function paymentTransaction()
    {
        if(isset(request()->type) && request()->type!='All'){
             $data = DB::table('payment_transaction')->
                join('customer','customer.cust_id','=','payment_transaction.userid')
                ->select('payment_transaction.*','customer.name')
                ->where(['payment_transaction.type'=>1,'payment_transaction.model_id'=>request()->type])
                ->orderBy('id','DESC')->paginate();
        }else{
              $data = DB::table('payment_transaction')->
                join('customer','customer.cust_id','=','payment_transaction.userid')
                ->select('payment_transaction.*','customer.name')
                ->where('payment_transaction.type','1')
                ->orderBy('id','DESC')->paginate();
        }
        
        $sub=_Subscriptions::select('title','amount','currency','id')->get();
        
        return view('subscriptions/payment_transaction',['data'=>$data,'sub'=>$sub]);
    }
    
    public function pendingApproval(){
        $sub = _Subscriptions::orderBy('id', 'DESC')->paginate();
      
        if(isset(request()->type) && request()->type!='All'){
             $data = DB::table('payment_proof')->
                join('customer','customer.cust_id','=','payment_proof.user_id')
                ->select('payment_proof.*','customer.name')
                ->where(['payment_proof.model_type'=>1,'payment_proof.model_id'=>request()->type,'payment_proof.status'=>0])
                ->orderBy('id','DESC')->paginate();
        }else{
              $data = DB::table('payment_proof')->
                join('customer','customer.cust_id','=','payment_proof.user_id')
                ->select('payment_proof.*','customer.name')
                ->where(['payment_proof.model_type'=>'1','payment_proof.status'=>0])
                ->orderBy('id','DESC')->paginate();
        }
        
        return view('subscriptions/pending',['data'=>$data,'sub'=>$sub]);
    }
    
    public function ApprovedOfflinePayment(){
        if(isset(request()->type) && request()->type!=''){
             $data = DB::table('payment_proof')->
                join('customer','customer.cust_id','=','payment_proof.user_id')
                ->select('payment_proof.*','customer.name')
                ->where(['payment_proof.model_type'=>1,'payment_proof.model_id'=>request()->type,'payment_proof.status'=>request()->type])
                ->orderBy('id','DESC')->paginate();
        }else{
              $data = DB::table('payment_proof')->
                join('customer','customer.cust_id','=','payment_proof.user_id')
                ->select('payment_proof.*','customer.name')
                ->where(['payment_proof.model_type'=>'1','payment_proof.status'=>1])
                ->orderBy('id','DESC')->paginate();
        }
        
        return view('subscriptions/approved',['data'=>$data]);
    }
    
    public function subApproval($id){
        
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }

        $paytrans=DB::table('payment_proof')->where('id',$id)->get();
        
        $subs=_Subscriptions::find($paytrans[0]->model_id);

        $user=Users::find($paytrans[0]->user_id);
        
        if($paytrans[0]->model_id==$user->subscription){
            return back()->withErrors(['msgError' => 'User Current Plan and Selected plan are Same.']);
        }
        
        $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=$paytrans[0]->model_id;
        $user->expire_sub=$paytrans[0]->model_id;
        $user->save();
        
        //insertsub
        $insertRecord=DB::table('subscribed_user')->insert([
            'user_id'=>$user->cust_id,
            'sub_id'=>$paytrans[0]->model_id,
            'validity'=>$subs->valid_for,
            'days'=>$day,
            'subscribed_at'=>$currentTime,
            'expired_at'=>$expiredAt,
            'amount'=>$subs->amount,
            'sub_info'=>$subs->title,
            'payment_mode'=>$paytrans[0]->payment_modal,
            'remark'=>'Manually Pay with '.$paytrans[0]->payment_modal
            ]);
            
        DB::table('payment_transaction')->insert([
            'userid' => $user->cust_id,
            'method' => $paytrans[0]->payment_modal,
            'trans_id' =>$paytrans[0]->transaction_id ,
            'amount' => ($subs->currency_posi == 0) ? $subs->currency . ' ' . $subs->amount : $subs->amount . ' ' . $subs->currency,
            'status' => 'approved',
            'model_id' => $paytrans[0]->model_id,
            'type' => 1,
            'pacinfo' => $paytrans[0]->modal_info
        ]);
         
        if($promo){
             DB::table('transaction')
                ->insert([
                    'tran_type' => 'credit',
                    'user_id' =>$paytrans[0]->user_id,
                    'amount' => $subs->promo_coin,
                    'type' => 'Promo Coin',
                    'remained_balance' => $total,
                    'inserted_at' => Carbon::now(),
                    'remarks' =>'Subscription Promo Coin Credit'
                ]);
        }
        
        DB::table('payment_proof')->where('id',$id)->update(['status'=>1,'updated_at'=>Carbon::now()]);
        
        DB::table('tbl_noti')->insert([
            'user_id'=>$paytrans[0]->user_id,
            'title'=>'Congratulations',
            'msg'=>'You are now '.$subs->title.' Member. your account has been upgraded.',
            'noti_type'=>0
            ]);
            
        DB::table('global_msg')->insert([
            'user_id'=>$paytrans[0]->user_id,
            'title'=>'Congratulations',
            'msg'=>'You are now '.$subs->title.' Member. your account has been upgraded.',
            'btn_name'=>'close',
            'btn_action'=>'close',
            'error'=>'false'
            ]);    
        
        return redirect('/subscriptions/pending-approval')->with('success','Account Upgrade Successfully !');
        
    }
    
    public function subReject(Request $req){
        
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }

        $paytrans=DB::table('payment_proof')->where('id',$req->id)->get();
        
        $subs=_Subscriptions::find($paytrans[0]->model_id);

        DB::table('payment_proof')->where('id',$req->id)->update(['status'=>2,'updated_at'=>Carbon::now()]);
        
        DB::table('tbl_noti')->insert([
            'user_id'=>$paytrans[0]->user_id,
            'title'=>$subs->title.' Payment has been Rejected',
            'msg'=>$req->remark,
            'noti_type'=>0
            ]);
            
        DB::table('global_msg')->insert([
            'user_id'=>$paytrans[0]->user_id,
            'title'=>$subs->title.' Payment has been Rejected',
            'msg'=>$req->remark,
            'btn_name'=>'Submit Again',
            'btn_action'=>'subscription',
            'error'=>'true'
            ]);    
        
        return redirect('/subscriptions/pending-approval')->with('success','Payment Rejected Successfully !');
                
    }

    
    public function store(Request $req){
            
        if(auth()->user()->role_create=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }
            
        if ($req->icon) {
            $filename =  Fun::StoreImage("image", null, null, $req, "icon", false);
            if ($filename == null) {
                return redirect('/subscriptions')->with('error', 'Technical Error in Image Upload');
            }
        } else {
            return redirect('/subscriptions')->with('error', 'Please Select Valid Image!');
        }

       $sub= new _Subscriptions;
       $sub->title=$req->title;
       $sub->image=$filename;
       $sub->description=$req->description;
       $sub->amount=$req->amount;
       $sub->country=$req->country;
       $sub->currency=$req->currency;
       $sub->currency_posi=$req->currency_posi;
       $sub->promo_coin=$req->promo_coin;
       $sub->valid_for=$req->valid_for;
       $sub->refer_bonus=$req->refer_bonus;
       $sub->task_web=$req->task_web;
       $sub->task_video=$req->task_video;
       $sub->task_videozone=$req->task_videozone;
       $sub->productID='sub_'. uniqid();
       $sub->task_quiz=$req->task_quiz;
       $sub->task_daily_offer=$req->task_daily_offer;
       $sub->task_spin=$req->task_spin;
       $sub->task_scratch=$req->task_scratch;
       $sub->save();
       
       return redirect('/subscriptions')->with('success','Subscriptions Plan Added Successfully');
    }
    
    public function update(Request $req){
        
        if(auth()->user()->role_edit=='false'){
            return redirect()->back()->withErrors(['msgError' =>DB::table('alias')->where('tag','permission_error')->get()->first()->description]);
        }
        
        if ($req->icon) {
            $filename =  Fun::StoreImage("image",null,null, $req, "icon", true);
            if ($filename == null) {
                return redirect('/subscriptions')->with('error', 'Technical Error in Image Upload');
            }
        } else {
            $filename=$req->oldicon;
        }
        
       $sub= _Subscriptions::find($req->id);
       $sub->title=$req->title;
       $sub->image=$filename;
       $sub->description=$req->description;
       $sub->amount=$req->amount;
       $sub->country=$req->country;
       $sub->currency=$req->currency;
       $sub->promo_coin=$req->promo_coin;
       $sub->valid_for=$req->valid_for;
       $sub->refer_bonus=$req->refer_bonus;
       $sub->task_web=$req->task_web;
       $sub->currency_posi=$req->currency_posi;
       $sub->task_video=$req->task_video;
       $sub->task_videozone=$req->task_videozone;
       $sub->task_quiz=$req->task_quiz;
       $sub->task_daily_offer=$req->task_daily_offer;
       $sub->task_spin=$req->task_spin;
       $sub->task_scratch=$req->task_scratch;
       $sub->save();
      
       return redirect('/subscriptions')->with('success', 'Update Successfully');
  
    }
    
    public function destroy($id)
    {
        if(auth()->user()->role_delete=='false'){
            return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
        }
        _Subscriptions::where('id', $id)->delete();
        return 1;
    }

    public function action(Request $req)
    {

        if ($req->status == "delete") {
            if(auth()->user()->role_delete=='false'){
                return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
            }
            
            $update = _Subscriptions::whereIn('id', explode(",", $req->id))->delete();
            if ($update) {
                return 1;
            } else {
                return "not updated";
            }
        } else if ($req->status == "enable") {
            if(auth()->user()->role_edit=='false'){
                return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
            }
                        
            $update = _Subscriptions::whereIn('id', explode(",", $req->id))->update(['status' => 0]);
            if ($update) {
                return 1;
            } else {
                return "not updated";
            }
        } else if ($req->status == "disable") {
            if(auth()->user()->role_edit=='false'){
                return DB::table('alias')->where('tag','permission_error')->get()->first()->description;
            }
            $update = _Subscriptions::whereIn('id', explode(",", $req->id))->update(['status' => 2]);
            if ($update) {
                return 1;
            } else {
                return "not updated";
            }
        }
    }
    
}