<?php

namespace App\Http\Controllers\User;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Config;
use App\Models\Setting;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Medias;
use App\Models\Optimer;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */

    // Dashboard
    public function index()
    {
        // User current plan details
        $plan = User::where('id', Auth::user()->id)->first();
        $active_plan = json_decode($plan->plan_details);

        // Queries
        $settings = Setting::where('status', 1)->first();
        $config = Config::get();

        // Initial Remaining days
        $remaining_days = 0;

        $current_storage = 0;

        // Subscription storage
        if (Auth::user()->plan_details != null) {
            $current_storage = json_decode(Auth::user()->plan_details)->storage;
        }

        // Get storage usage
        $storageUsage = Medias::where('user_id', Auth::user()->id)->where('status', 1)->sum('size');

        // Get User optimize image
        $optimers = Optimer::where('uploaded_by', Auth::user()->id)->where('status', 1)->orderBy('id', 'desc')->limit(10)->get();

        // Get today optimize image count
        $today_optimers_count = Optimer::where('uploaded_by', Auth::user()->id)->whereDate('created_at', Carbon::today())->count();

        // Get today optimize image size
        $today_optimized_image_size = Optimer::where('uploaded_by', Auth::user()->id)->whereDate('created_at', Carbon::today())->sum('optimized_image_size');

        // Check active plan
        if ($active_plan != null) {
            if (isset($active_plan)) {
                $plan_validity = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', Auth::user()->plan_validity);
                $current_date = Carbon::now();

                // Remaining dates
                $remaining_days = $current_date->diffInDays($plan_validity, false);
            }

            return view('user.index', compact('settings', 'active_plan', 'remaining_days', 'optimers', 'today_optimers_count', 'storageUsage', 'current_storage', 'today_optimized_image_size', 'settings', 'config'));
        } else {
            // Redirect plan
            return redirect()->route('user.plans');
        }
    }
}
