<?php

namespace App\Http\Controllers\LicenseManagement;

use DB;
use Hash;
use Carbon\Carbon;
use App\Models\Account;
use App\Models\Company;
use App\Models\Projects;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use App\Models\VoucherMaster;
use App\Models\LicenseDetail;
use App\Exports\ClientReport;
use App\Exports\RenewalReport;
use App\Exports\LicenseReport;
use App\Exports\RevenueReport;
use App\Exports\ServicesReport;
use App\Models\LmsClassSection;
use Yajra\DataTables\DataTables;
use App\Models\LicenseRegistered;
use Spatie\Permission\Models\Role;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use App\Models\LicenseActivationHistory;

class LicenseRegisteredController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:license-registered-list|license-registered-create|license-registered-edit|license-registered-delete', ['only' => ['index', 'store', 'revenueReport']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $option = '')
    {
        $data = LicenseRegistered::query();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('license_no', 'like', '%' . $search_query . '%');
            })
                ->orderBy('id', 'DESC')
                ->groupBy('id')
                ->paginate($sort_by);

            return view('license-registered.table', compact('data'));
        } else {

            if ($option == 'export') {
                return $data->orderBy('id', 'DESC')->get();
            }

            $data = $data->groupBy('id')
                ->orderBy('id', 'DESC')
                ->paginate(10);

            return view('license-registered.index', compact('data'));
        }
    }

    public function dashboard(Request $request)
    {
        if (!$this->checkPermission('license-registered-list')) {
            return redirect()->back()->with('info', 'You don\'t have enough permission to access this page.');
        }

        $totalLicense      = LicenseRegistered::count();
        $totalClients      = LicenseRegistered::groupBy('bill_to_account_id')->get()->count();
        $totalMainServices = LicenseDetail::where('type', 'Main')->count();
        $totalAddon        = LicenseDetail::where('type', 'Add-on')->count();

        // Renewal data.
        $recordsThisWeek = LicenseActivationHistory::whereBetween('expiry_date', [
            Carbon::now()->startOfWeek()->format('Y-m-d H:i:s'),
            Carbon::now()->endOfWeek()->format('Y-m-d H:i:s'),
        ])->count();

        $recordsThisMonth = LicenseActivationHistory::select('*', 'license_details.billing_interval_id')
            ->leftJoin('license_details', 'license_details.id', 'license_activation_histories.license_id')
            ->where('license_details.billing_interval_id', 2)
            ->whereBetween('expiry_date', [
                Carbon::now()->startOfMonth()->format('Y-m-d'),
                Carbon::now()->endOfMonth()->format('Y-m-d'),
            ])->count();

        $recordsThisQuarter = LicenseActivationHistory::select('*', 'license_details.billing_interval_id')
            ->leftJoin('license_details', 'license_details.id', 'license_activation_histories.license_id')
            ->where('license_details.billing_interval_id', 3)
            ->whereBetween('expiry_date', [
                Carbon::now()->startOfQuarter()->format('Y-m-d H:i:s'),
                Carbon::now()->endOfQuarter()->format('Y-m-d H:i:s'),
            ])->count();

        // Assuming the half-year starts from January to June and July to December
        $currentMonth = Carbon::now()->month;

        if ($currentMonth <= 6) {
            $recordsThisHalfYear = LicenseActivationHistory::select('*', 'license_details.billing_interval_id')
                ->leftJoin('license_details', 'license_details.id', 'license_activation_histories.license_id')
                ->where('license_details.billing_interval_id', 4)
                ->whereBetween('expiry_date', [
                    Carbon::now()->startOfYear()->format('Y-m-d H:i:s'),
                    Carbon::now()->endOfMonth()->setMonth(6)->format('Y-m-d H:i:s'),
                ])->count();
        } else {
            $recordsThisHalfYear = LicenseActivationHistory::select('*', 'license_details.billing_interval_id')
                ->leftJoin('license_details', 'license_details.id', 'license_activation_histories.license_id')
                ->where('license_details.billing_interval_id', 4)
                ->whereBetween('expiry_date', [
                    Carbon::now()->startOfMonth()->setMonth(7)->format('Y-m-d H:i:s'),
                    Carbon::now()->endOfYear()->format('Y-m-d H:i:s'),
                ])->count();
        }

        // Revenue data.
        $monthlyRevenue    = LicenseRegistered::select(
            \DB::raw('SUM(license_details.taxable_rate) AS revenue')
        )
            ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
            ->where('license_details.billing_interval_id', 2)
            ->first();

        $quarterlyRevenue  = LicenseRegistered::select(
            \DB::raw('SUM(license_details.taxable_rate) AS revenue')
        )
            ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
            ->where('license_details.billing_interval_id', 3)
            ->first();

        $halfYearlyRevenue = LicenseRegistered::select(
            \DB::raw('SUM(license_details.taxable_rate) AS revenue')
        )
            ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
            ->where('license_details.billing_interval_id', 4)
            ->first();

        $yearlyRevenue = $halfYearlyRevenue->revenue * 2;
        $roles         = \Auth::user()->roles;
        $roleNames    = [];

        foreach ($roles as $role) {
            // Access role properties or methods
            $roleNames[] = $role->name;
        }

        return view('license-registered.dashboard', compact(
            'roleNames',
            'monthlyRevenue',
            'quarterlyRevenue',
            'halfYearlyRevenue',
            'yearlyRevenue',
            'recordsThisWeek',
            'recordsThisMonth',
            'recordsThisQuarter',
            'recordsThisHalfYear',
            'totalLicense',
            'totalClients',
            'totalMainServices',
            'totalAddon',
        ));
    }

    public function revenueReport(Request $request, $type = '', $option = '')
    {
        // revenue-table
        if (!$type) {
            abort(404);
        }

        // Revenue data.
        if ($type == 'monthly') {

            $data = LicenseRegistered::select(
                'license_registereds.*',
                'license_details.billing_interval_id',
                'license_details.taxable_rate',
                'license_activation_histories.expiry_date',
                // \DB::raw('SUM(license_details.taxable_rate) AS revenue')
            )
                ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
                ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
                ->where('license_details.billing_interval_id', 2);
        } elseif ($type == 'quarterly') {

            $data  = LicenseRegistered::select(
                'license_registereds.*',
                'license_details.billing_interval_id',
                'license_details.taxable_rate',
                'license_activation_histories.expiry_date',
                // \DB::raw('SUM(license_details.taxable_rate) AS revenue')
            )
                ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
                ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
                ->where('license_details.billing_interval_id', 3);
        } elseif ($type == 'half-yearly') {

            $data = LicenseRegistered::select(
                'license_registereds.*',
                'license_details.billing_interval_id',
                'license_details.taxable_rate',
                'license_activation_histories.expiry_date',
                // \DB::raw('SUM(license_details.taxable_rate) AS revenue')
            )
                ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
                ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
                ->where('license_details.billing_interval_id', 4);
        } elseif ($type == 'yearly') {
            $data = LicenseRegistered::select(
                'license_registereds.*',
                'license_details.billing_interval_id',
                'license_details.taxable_rate',
                'license_activation_histories.expiry_date',
                \DB::raw('(license_details.taxable_rate * 2) AS taxable_rate')
            )
                ->leftJoin('license_details', 'license_details.order_id', 'license_registereds.id')
                ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
                ->where('license_details.billing_interval_id', 4);
        }

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('license_no', 'like', '%' . $search_query . '%');
            })
                ->orderBy('bill_to_account_id', 'ASC')
                ->get();

            return view('license-registered.revenue-table', compact('data'));
        } else {

            if ($option == 'export') {
                return $data->orderBy('bill_to_account_id', 'ASC')->get();
            }

            $data = $data
                ->orderBy('bill_to_account_id', 'ASC')
                ->get();

            return view('license-registered.revenue-report', compact('data'));
        }

        //   return view('license-registered.revenue-report');
    }

    public function renewalReport(Request $request, $type = '', $option = '')
    {
        $dates = [];
        $data = $data = LicenseActivationHistory::select(
            'license_activation_histories.*',
            'license_registereds.license_no',
            'license_registereds.license_date',
            'license_details.billing_interval_id',
            'accounts.name',
            'account_contacts.email',
            'account_contacts.phone_no',
            'account_contacts.whatsapp_no',
        )
            ->leftJoin('license_details', 'license_details.id', 'license_activation_histories.license_id')
            ->leftJoin('license_registereds', 'license_registereds.id', 'license_details.order_id')
            ->leftJoin('accounts', 'accounts.id', 'license_registereds.bill_to_account_id')
            ->leftJoin('account_contacts', 'account_contacts.account_id', 'accounts.id')
            ->orderBy('bill_to_account_id', 'ASC');
        // Renewal data.
        if ($type == 'week') {
            $dates = [
                Carbon::now()->startOfWeek()->format('Y-m-d'),
                Carbon::now()->endOfWeek()->format('Y-m-d'),
            ];

            $data = $data->whereBetween('expiry_date', $dates)
                ->groupBy('license_activation_histories.id');
        } elseif ($type == 'month') {
            $dates = [
                Carbon::now()->startOfMonth()->format('Y-m-d'),
                Carbon::now()->endOfMonth()->format('Y-m-d'),
            ];

            $data = $data->where('license_details.billing_interval_id', 2)
                ->whereBetween('expiry_date', $dates)
                ->groupBy('license_activation_histories.id');
        } elseif ($type == 'quarter') {
            $dates = [
                Carbon::now()->startOfQuarter()->format('Y-m-d'),
                Carbon::now()->endOfQuarter()->format('Y-m-d'),
            ];

            $data = $data->where('license_details.billing_interval_id', 3)
                ->whereBetween('expiry_date', $dates)
                ->groupBy('license_activation_histories.id');
        } elseif ($type == 'half-yearly') {
            // Assuming the half-year starts from January to June and July to December
            $currentMonth = Carbon::now()->month;
            $dates = [
                Carbon::now()->startOfYear()->format('Y-m-d'),
                Carbon::now()->endOfMonth()->setMonth(6)->format('Y-m-d'),
            ];

            if ($currentMonth <= 6) {
                $data = $data->where('license_details.billing_interval_id', 4)
                    ->whereBetween('expiry_date', $dates)
                    ->groupBy('license_activation_histories.id');
            } else {
                $dates = [
                    Carbon::now()->startOfMonth()->setMonth(7)->format('Y-m-d'),
                    Carbon::now()->endOfYear()->format('Y-m-d'),
                ];

                $data = $data->where('license_details.billing_interval_id', 4)
                    ->whereBetween('expiry_date', $dates)
                    ->groupBy('license_activation_histories.id');
            }
        }

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('license_no', 'like', '%' . $search_query . '%');
            })
                // ->groupBy('license_registereds.id')
                ->get();

            return view('license-registered.renewal-table', compact('data'));
        } else {

            if ($option == 'export') {
                return $data->get();
            }

            $data = $data
                // ->groupBy('license_registereds.id')
                ->get();

            return view('license-registered.renewal-report', compact('data', 'dates'));
        }
    }

    public function exportRenewalReport(Request $request)
    {
        $filename = "renewal-report_" . date("Y_m_d_i_H") . ".xlsx";
        return Excel::download(new RenewalReport, $filename);
    }

    public function exportRevenueReport(Request $request)
    {
        $filename = "revenue-report_" . date("Y_m_d_i_H") . ".xlsx";
        return Excel::download(new RevenueReport, $filename);
    }

    public function exportLicenseReport(Request $request)
    {
        $filename = "license-report_" . date("Y_m_d_i_H") . ".xlsx";
        return Excel::download(new LicenseReport, $filename);
    }

    public function exportServiceReport(Request $request)
    {
        $filename = "services-report_" . date("Y_m_d_i_H") . ".xlsx";
        return Excel::download(new ServicesReport, $filename);
    }

    public function exportClientReport(Request $request)
    {
        $filename = "services-report_" . date("Y_m_d_i_H") . ".xlsx";
        return Excel::download(new ClientReport, $filename);
    }

    public function licenseReport(Request $request, $type = '', $option = '')
    {
        if (!$type) {
            abort(404);
        }

        // $totalLicense      = LicenseRegistered::count();
        // $totalClients      = LicenseRegistered::groupBy('bill_to_account_id')->get()->count();
        // $totalMainServices = LicenseDetail::where('type', 'Main')->count();
        // $totalAddon        = LicenseDetail::where('type', 'Add-on')->count();
        if ($type == 'clients') {
            $data = LicenseRegistered::with('license_detail')->groupBy('bill_to_account_id');
        }

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('license_no', 'like', '%' . $search_query . '%');
            })
                ->orderBy('bill_to_account_id', 'ASC')
                // ->groupBy('license_registereds.id')
                ->get();

            return view('license-registered.report-table', compact('data'));
        } else {

            if ($option == 'export') {
                return $data->orderBy('billing_company_id', 'ASC')->get();
            }

            $data = $data
                // ->groupBy('license_registereds.id')
                ->orderBy('billing_company_id', 'ASC')
                ->get();

            return view('license-registered.report', compact('data'));
        }
    }

    public function serviceReport(Request $request, $type = '', $option = '')
    {
        $data = LicenseDetail::select(
            'license_details.*',
            'license_registereds.license_no',
            'license_registereds.license_date',
            'license_registereds.order_date',
            'license_activation_histories.expiry_date',
            'license_registereds.bill_to_account_id',
            'accounts.name',
            'account_contacts.email',
            'account_contacts.phone_no',
            'account_contacts.whatsapp_no',
        )
            ->leftJoin('license_registereds', 'license_registereds.id', 'license_details.order_id')
            ->leftJoin('license_activation_histories', 'license_activation_histories.license_id', 'license_details.id')
            ->leftJoin('accounts', 'accounts.id', 'license_registereds.bill_to_account_id')
            ->leftJoin('account_contacts', 'account_contacts.account_id', 'accounts.id')
            ->orderBy('bill_to_account_id', 'ASC');

        if ($type == 'main') {
            $data = $data->where('type', 'Main');
        } elseif ($type == 'add-on') {
            $data = $data->where('type', 'Add-on');
        }

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('license_no', 'like', '%' . $search_query . '%');
            })
                ->get();

            return view('license-registered.service-table', compact('data'));
        } else {

            if ($option == 'export') {
                return $data->orderBy('bill_to_account_id', 'ASC')->get();
            }

            $data = $data->get();

            return view('license-registered.service-report', compact('data'));
        }
    }

    public function list(Request $request)
    {
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $partners = Account::select(
            'accounts.*',
            'account_types.type_name',
            'accounting_groups.name as group_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->leftjoin('accounting_groups', 'accounting_groups.id', 'accounts.accounting_group_id')
            ->where('type_code', 'REFERRAL_PARTNER')
            ->where('accounting_groups.code', 'SUNDRY_CREDITORS')
            ->get();

        $agents = Account::select(
            'accounts.*',
            'account_types.type_name',
            'accounting_groups.name as group_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->leftjoin('accounting_groups', 'accounting_groups.id', 'accounts.accounting_group_id')
            ->where('account_types.type_code', 'SALES_AGENT')
            ->where('accounting_groups.code', 'SUNDRY_CREDITORS')
            ->get();

        $managers = Account::select(
            'accounts.*',
            'account_types.type_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->where('type_code', 'EMPLOYEE')
            ->get();

        $projects  = Projects::get();
        $companies = Company::get();
        $customers = Account::select([
            'accounts.*',
            'account_types.type_name',
        ])
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->where('type_code', 'CUSTOMER')
            ->groupBy('accounts.id')
            ->get();

        return view('license-registered.create', compact(
            'agents',
            'managers',
            'partners',
            'customers',
            'companies',
            'projects'
        ));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'order_date'         => 'required',
            'license_date'       => 'required',
            // 'license_no'      => 'required',
            // 'project_code'    => 'required',
            'project_id'         => 'required',
            'bill_to_account_id' => 'required',
            'ship_to_account_id' => 'required',
            'billing_company_id' => 'required',
            // 'license_note'       => 'required',
            // 'client_remarks'     => 'required'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token']);

        $voucher_master = VoucherMaster::with('voucherSeries')
            ->where('voucher_code', 'SALES')
            ->where(['status' => 1])
            ->first();
        # last voucher count for main invoice number
        $license_count = LicenseRegistered::select('last_issue_count')
            ->orderBy('created_at', 'DESC')
            ->first();

        $last_issue_count = isset($license_count) && isset($license_count->last_issue_count) ? $license_count->last_issue_count + 1 : ($voucher_master->voucherSeries->start_from + 1 ?? 1);
        $main_invoice_no = $this->generateCode(
            $last_issue_count,
            (''),
            (''),
            (''),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        $data['license_no'] = $this->generateCode(
            $last_issue_count,
            ('MMLN'),
            ($voucher_master->voucherSeries->postfix ?? ''),
            ($voucher_master->voucherSeries->separator ?? '-'),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        $data['last_issue_count'] = $main_invoice_no;

        $order_date           = \DateTime::createFromFormat('m-d-Y', $request->order_date);
        $data['order_date']   = date('Y-m-d', $order_date->getTimestamp());

        $licenseDate          = \DateTime::createFromFormat('m-d-Y', $request->license_date);
        $data['license_date'] = date('Y-m-d', $licenseDate->getTimestamp());
        // $data['license_key']    = 'lk' . $this->generateRandomCode(10);
        // $data['license_secret'] = 'ls' . $this->generateRandomCode(10);
        $data['license_key'] = $this->generateRandomCode(4);
        $data['license_secret'] = $this->generateRandomCode(4);
        // echo '<pre>';
        // print_r($data['license_key']);
        // echo '<br>';
        // $letter_count_key = strlen($data['license_key']); // Calculating length of license key
        // echo  $letter_count_key; // Displaying license key length
        // echo '<br>';
        // print_r($data['license_secret']);
        // echo '<br>';
        // $letter_count_secret = strlen($data['license_secret']); // Calculating length of license secret
        // echo $letter_count_secret; // Displaying license secret length
        // echo '</pre>';
        // die();


        $data = LicenseRegistered::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'License has been registered successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('license-register.index')
            ->with('success', 'License has been registered successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $partners = Account::select(
            'accounts.*',
            'account_types.type_name',
            'accounting_groups.name as group_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->leftjoin('accounting_groups', 'accounting_groups.id', 'accounts.accounting_group_id')
            ->where('type_code', 'REFERRAL_PARTNER')
            ->where('accounting_groups.code', 'SUNDRY_DEBTORS')
            ->get();

        $agents = Account::select(
            'accounts.*',
            'account_types.type_name',
            'accounting_groups.name as group_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->leftjoin('accounting_groups', 'accounting_groups.id', 'accounts.accounting_group_id')
            ->where('type_code', 'SALES_AGENT')
            ->where('accounting_groups.code', 'SUNDRY_CREDITORS')
            ->get();

        $managers = Account::select(
            'accounts.*',
            'account_types.type_name'
        )
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->where('type_code', 'EMPLOYEE')
            ->get();

        $projects  = Projects::get();
        $data      = LicenseRegistered::find($id);
        $companies = Company::get();
        $customers = Account::select([
            'accounts.*',
            'account_types.type_name',
        ])
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->where('type_code', 'CUSTOMER')
            ->groupBy('accounts.id')
            ->get();

        return view('license-registered.edit', compact(
            'data',
            'agents',
            'managers',
            'partners',
            'companies',
            'projects',
            'customers'
        ));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'order_date'         => 'required',
            'license_date'       => 'required',
            // 'license_no'      => 'required',
            // 'project_code'    => 'required',
            'project_id'         => 'required',
            'bill_to_account_id' => 'required',
            'ship_to_account_id' => 'required',
            'billing_company_id' => 'required',
            // 'license_note'       => 'required',
            // 'client_remarks'     => 'required'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $license = LicenseRegistered::find($id);
        $data    = $request->except(['_token', '_method']);

        $order_date           = \DateTime::createFromFormat('m-d-Y', $request->order_date);
        $data['order_date']   = date('Y-m-d', $order_date->getTimestamp());

        $licenseDate          = \DateTime::createFromFormat('m-d-Y', $request->license_date);
        $data['license_date'] = date('Y-m-d', $licenseDate->getTimestamp());

        $data = $license->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'License has been updated successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('license-register.index')
            ->with('success', 'License has been updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = LicenseRegistered::find($request->id);

        LicenseRegistered::find($request->id)->delete();

        $Redirect = 'student-house';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('license_status' => $request->status);
            $Update = LicenseRegistered::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['House status successfully change'],
                    'data' => [
                        'redirect' => '/student-house/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function generateLicenseNumber()
    {
        $voucher_master = VoucherMaster::with('voucherSeries')
            ->where('voucher_code', 'SALES')
            ->where(['status' => 1])
            ->first();

        # last voucher count for main invoice number
        $license_count = LicenseRegistered::select('last_issue_count')
            ->orderBy('created_at', 'DESC')
            ->first();

        $last_issue_count = isset($license_count) && isset($license_count->last_issue_count) ? $license_count->last_issue_count + 1 : ($voucher_master->voucherSeries->start_from + 1 ?? 1);

        $main_invoice_no = $this->generateCode(
            $last_issue_count,
            ('MMLN'),
            ($voucher_master->voucherSeries->postfix ?? ''),
            ($voucher_master->voucherSeries->separator ?? '-'),
            ($voucher_master->voucherSeries->length ?? 5)
        );

        return response()->json(['license' => $main_invoice_no]);
    }

    public function customerSelect(Request $request)
    {
        $searchTerm = $request->search_text;
        $results    =  Account::select([
            'accounts.*',
            'account_types.type_name',
        ])
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
            ->where('type_code', 'CUSTOMER')
            ->groupBy('accounts.id')
            ->get();
        return response()->json(['result' => $results, 'status' => true]);
    }

    public function licenseKeys($id)
    {
        $license = LicenseRegistered::select('license_key', 'license_secret', 'license_date')->find($id);

        if ($license) {
            return view('license-registered.keys', compact(
                'license'
            ));
        }

        return redirect()->back()->with('error', "Invalid License ID!");
    }

}
