<?php

namespace App\Http\Controllers;

use App\Models\CompanyAddress;
use App\Models\Enquiry;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\LicenseDetail;
use App\Models\LicenseRegistered;
use App\Models\LicenseActivationHistory;
use App\Models\FinancialYear;
use App\Models\Product;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

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
     */
    public function index()
    {
        $bookCount       = $userCount = $categoryCount = $returnCount = 0;
        $company_id      = \Auth::user()->company_id ?? 0;
        $financial_years = count(\Session::get('financialyear'));
        $financial_year = Session::get('financialyear');

        $productCount    = Product::count();
        // $enquiryCount    = Enquiry::count();
        $enquiryCount    = 0;

        if ($financial_years < 1) {
            // dd('test');
            $this->setCurrentFinancialYear();
            return redirect('dashboard');
        }

        if (isset($financial_year[0]) && isset($financial_year[0]->financial_year_end_date) &&
            $financial_year[0]->financial_year_end_date < date('Y-m-d')) {
            $this->setCurrentFinancialYear();
            return redirect('dashboard');
        }

        return view('admin.dashboard')->with([
            // 'roleNames'           => $roleNames,
            // 'monthlyRevenue'      => $monthlyRevenue,
            // 'quarterlyRevenue'    => $quarterlyRevenue,
            // 'halfYearlyRevenue'   => $halfYearlyRevenue,
            // 'yearlyRevenue'       => $yearlyRevenue,
            // 'recordsThisWeek'     => $recordsThisWeek,
            // 'recordsThisMonth'    => $recordsThisMonth,
            // 'recordsThisQuarter'  => $recordsThisQuarter,
            // 'recordsThisHalfYear' => $recordsThisHalfYear,
            // 'totalLicense'        => $totalLicense,
            // 'totalClients'        => $totalClients,
            // 'totalMainServices'   => $totalMainServices,
            // 'totalAddon'          => $totalAddon,
            'bookCount'       => $bookCount,
            'userCount'       => $userCount,
            'categoryCount'   => $categoryCount,
            'returnCount'     => $returnCount,
            'financial_years' => $financial_years,
            'productCount'    => $productCount,
            'enquiryCount'    => $enquiryCount,
        ]);
    }

    public function setCurrentFinancialYear()
    {
        $company_id      = Auth::user()->company_id ?? '';
        $company_address = CompanyAddress::select('id','country_id')->with(['getComapnyCountry' => function ($query) {
            $query->select('id','financial_year_start_month', 'financial_year_start_date','financial_year_end_month','financial_year_end_date');
        }])
        ->where('company_id', $company_id)
        ->orWhere('is_default', '1')
        ->first();
        $year = date('Y');
        $startedDate    = $year . '-' . (($company_address->getComapnyCountry->financial_year_start_month ?? '') . '-' . ($company_address->getComapnyCountry->financial_year_start_date ?? '' ));
        //1st April
        $endDate        = $year . '-' . (($company_address->getComapnyCountry->financial_year_end_month ?? '') . '-' . ($company_address->getComapnyCountry->financial_year_end_date ?? ''));
        //31st March

        $startedTimestamp = strtotime($startedDate);
        $endTimestamp = strtotime($endDate);

        if ($startedTimestamp > $endTimestamp) {
            $startedDate = ($year - 1 ) . substr($startedDate, 4);
            $endDate = ($year ) . substr($endDate, 4);
        }

        if ($startedDate < date('Y-m-d')) {
            $startedDate = ($year ) . substr($startedDate, 4);
            $endDate = ($year + 1 ) . substr($endDate, 4);
        }

        FinancialYear::where(['company_id' => $company_id])->update(['is_default' => '0']);

        $financial_year = FinancialYear::create([
            'financial_year_start_date' => $startedDate,
            'financial_year_end_date'   => $endDate,
            'company_id'                => $company_id,
            'status'                    => 1,
            'is_default'                => '1',
        ]);

        $data   = array('my_financial_year_id' => $financial_year->financialyearid);
        $Update = User::where('id', '=', \Auth()->id())->update($data);

        $financial_year = FinancialYear::where(['company_id' => Auth::user()->company_id, 'status' => '1'])
        ->latest()->first();

        Session::put('financial_year', $financial_year);

        $financialyear_id = Auth::user()->my_financial_year_id;

        if (empty($financialyear_id) && $company_id) {
            $financialyear = FinancialYear::select('financialyearid')->where(['company_id' => $company_id, 'status' => '1'])
                ->orderBy('is_default', 'desc')
                ->first();

            $financialyear_id = $financialyear->financialyearid ?? '';
        }

        Session::put('user_financial_year_id', $financialyear_id);

        $financialyear = FinancialYear::select([
                'financialyearid',
                'financial_year_name',
                'company_id',
                'status',
                'is_default',
            ])
            ->where([
                'company_id' => $company_id,
                'status'     => '1'
            ])
            ->orderBy('is_default', 'desc')
            ->get();

        Session::put('financialyear', $financialyear);
    }
}
