<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Plan;
use App\Models\UsageLimit;
use App\Models\UserUsage;
use DB;

class PlanController extends Controller
{
    public function plans()
    {
        $list = Plan::select('id','name','price','interval','points','note')->get()->map(function ($plan) {
                        $plan->points = json_decode($plan->points, true) ?? [];
                        return $plan;
                    });

        return response()->json([
            'success'   => true,
            'message'   => 'Plan Data',
            'list'      => $list,
        ], 200);
    }
    
    public function myPlan(Request $request)
    {
        //User Usage Start
        $usages = $this->userUsages($request);
        //User Usage Ens

        
        $user       = $request->user();
        $checkSub   = DB::table('subscriptions')->where(['user_id'=>$user->id,'status'=>'active'])->orderBy('created_at','DESC')->first();
        if($checkSub==null)
        {
            $ul_id  = env('DEFAULT_UL_ID');
            $limits = UsageLimit::select('id','word_limit', 'word_limit_durection','voice_limit','voice_limit_durection','image_limit','image_limit_durection','device_limit')->where('id',$ul_id)->first();
            return response()->json([
                'success'   => false,
                'message'   => "No Plan Exist",
                'plan'      => new \stdClass(),
                'usagesMaster'  => array('limits'=> $limits,'usages'=> $usages)
            ],200);
        }
        else
        {
            $plan   = Plan::select('id','name','price','interval','points','ul_id')
                            ->with(['usageLimit' => function ($q) {
                                $q->select('id','word_limit', 'word_limit_durection','voice_limit','voice_limit_durection','image_limit','image_limit_durection','device_limit');
                            }])
                            ->where('id',$checkSub->plan_id)
                            ->first();
            
            $plan->points   = json_decode($plan->points, true) ?? [];
            if(isset($checkSub->is_trial) && $checkSub->is_trial==1)
            {
                $plan->name     = 'Free Trial';
                $plan->price    = '0.00';
                $plan->interval = '';
                
            }
            $plan->start_date   = $checkSub->start_at;
            $plan->end_date     = $checkSub->end_at;
            $plan->is_trial     = $checkSub->is_trial ?? '0';
            $limits             = $plan->usageLimit;
            unset($plan->usageLimit);
            return response()->json([
                'success'   => true,
                'message'   => "Plan Details",
                'plan'      => $plan,
                'usagesMaster'  => array('limits'=> $limits,'usages'=> $usages)
            ],200);
        }
    }

    public function userUsages($request)
    {
        $user_id    = $request->user()->id;
        $date       = now()->format('Y-m-d');
        //
        $wordRecord = UserUsage::where('type', 'word')
                        ->select('type','usage','record_date')
                        ->whereDate('record_date', $date)
                        ->where('user_id',$user_id)
                        ->latest('record_date')
                        ->first();
        if($wordRecord==null) {
            $wordRecord         = new \stdClass();
            $wordRecord->type   = 'word';
            $wordRecord->usage  = '0';
            $wordRecord->record_date = $date;
        }

        //
        $audioRecord    = UserUsage::where('type', 'audio')
                            ->select('type','usage','record_date')
                            ->whereDate('record_date', $date)
                            ->where('user_id',$user_id)
                            ->latest('record_date')
                            ->first();
        if($audioRecord==null) {
            $audioRecord        = new \stdClass();
            $audioRecord->type  = 'audio';
            $audioRecord->usage = '0';
            $audioRecord->record_date = $date;
        }
        else{
            $minutes = floor($audioRecord->usage / 60);
            $remainingSeconds = $audioRecord->usage % 60;
            $audioRecord->usage = $minutes.'.'.$remainingSeconds;
        }

        //
        $imageRecord    = UserUsage::where('type', 'image')
                            ->select('type','usage','record_date')
                            ->whereYear('record_date', now()->year)
                            ->whereMonth('record_date', now()->month)
                            ->where('user_id',$user_id)
                            ->latest('record_date')
                            ->first();

        if ($imageRecord==null) {
            $imageRecord        = new \stdClass();
            $imageRecord->type  = 'image';
            $imageRecord->usage = '0';
            $imageRecord->record_date = $date;
        }

        return array('word'=>$wordRecord,'audio'=>$audioRecord,'image'=>$imageRecord);
        
    }
}
