<?php

namespace Database\Seeders;

use App\Models\Account;
use App\Models\AccountingGroup;
use App\Models\AccountSettlementType;
use App\Models\Company;
use App\Models\LicenseDetail;
use App\Models\LicenseRegistered;
use App\Models\MasterCategory;
use App\Models\MasterType;
use App\Models\PlaneAndPackages;
use App\Models\Projects;
use App\Models\Server;
use App\Models\VoucherMaster;
use App\Models\TaxRegisterCategory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class LicenseRegisteredTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ProjectTableSeeder::class);
        $this->call(PlanAndPackagesTableSeeder::class);
        $this->call(ServerTableSeeder::class);

        $accountType              = MasterType::where('type_name', 'Customer')->first();
        $accountCategory          = MasterCategory::where('category_name', 'General')->first();
        $accountGroup             = AccountingGroup::where('name', 'Sundry Debtors')->first();
        $taxRegisterCategory      = TaxRegisterCategory::where('name','Regular Registration')->first();
        $account_settlement_types = AccountSettlementType::where('name','BILL TO BILL')->first();

       $CustomerAccount = [
            'account_type_id'          => $accountType->id ?? '',
            'account_category_id'      => $accountCategory->id ?? '',
            'accounting_group_id'      => $accountCategory->id ?? '',
            'accounting_group_id'      =>  $accountGroup->id ?? '',
            'division_id'              => null,
            'company_id'               => 1,
            'tax_register_category_id' => $taxRegisterCategory->id ?? '',
            'name'                     => 'Meta Mint Private Limited',
            'code'                     => 'METAMINT',
            'settlement_type'          => $account_settlement_types->id ?? '',
            'balance_type'             => null,
            'opening_balance'          => 0.00,
            'print_name'               => "Meta Mint Private Limited",
            'referred_by'              => null,
            'account_title_id'         => null,
            'created_at'               => now(),
        ];

        $customer = Account::firstOrCreate(
            ['name' => $CustomerAccount['name']],
            $CustomerAccount
        );

        $project = Projects::where('title','MetaMint')->first();
        // $customer  = Account::where('account_type_id',10)->first();
        $company = Company::where('name','Meta Mint Private Limited')->first();

        $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;
        $data['license_key']    = 'lk'.\Str::random(10);
        $data['license_secret'] = 'ls'.\Str::random(10);

       $license = [

            'order_date'         => now(),
            'license_date'       => now(),
            'license_no'         => $data['license_no'],
            'license_secret'     => $data['license_secret'],
            'license_key'        => $data['license_key'],
            'project_code'       => $project->code,
            'bill_to_account_id' => $customer->id,
            'ship_to_account_id' => $customer->id,
            'billing_company_id' => $company->id,
            'license_note'       => null,
            'client_remarks'     => null,
            'last_issue_count'   => 1,
            'project_id'         => $project->id,
            'created_at'         => now(),

        ];
           $licenseRegistered =  LicenseRegistered::firstOrCreate(
                ['license_no' => $license['license_no']],
                $license
            );

            $planPackages = PlaneAndPackages::where('plan_name','Meta Mint')->first();
            $server       = Server::where('server_name','Meta Mint Cloud')->first();
            // $order        = LicenseDetail::select('order_id',+1);

           $licenseDetails = [
                    'order_id'             => $licenseRegistered->id,
                    'product_token_no'     => \Str::uuid(),
                    'server_id'            => $server->id,
                    'front_end_url'        => null,
                    'back_end_url'         => null,
                    'product_id'           => null,
                    'product_price_id'     => null,
                    'billing_interval_id'  => 1,
                    'plan_and_packages_id' => $planPackages->id,
                    'quantity'             => null,
                    'taxable_rate'         => null,
                    'discount_type'        => null,
                    'discount_value'       => null,
                    'registration_date'    => now(),
                    'first_activation'     => now(),
                    'billing_start_date'   => now(),
                    'production'           => 'live',
                    'maintenance_mode'     => 1,
                    'type'                 => 'Main',
                    'created_at'           => now(),
            ];


            LicenseDetail::firstOrCreate(
                ['product_token_no' => $licenseDetails['product_token_no']],
                $licenseDetails
            );
    }
    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 generateCode($id, $prefix, $postfix = '', $seperator = '', $length = '5')
    {
        $paddedId      = str_pad($id, $length, '0', STR_PAD_LEFT);
        $generatedCode = ($postfix == '') ? $prefix . $seperator . $paddedId : $prefix . $seperator . $paddedId . $seperator . $postfix;

        $account = Account::where('code', $generatedCode)->first();

        if ($account) {
            $id = $id + 1;
            $generatedCode = $this->generateCode($id, $prefix, $postfix, $seperator, $length);
        }

        return $generatedCode;
    }
}
