<?php

namespace App\Imports;

use App\Models\BillGenerate;
use App\Models\Client;
use App\Models\CustomerAccount;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;

class ClientdueImport implements ToCollection
{
    use Importable;
    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {
        $rowNumber = 1;
        for ($i = 1; $i < count($rows); $i++) {
            $row = $rows[$i];

            $rowNumber++;

            $customRules = [
                '0' => 'required',
                '1' => 'required',
            ];

            $customAttributes = [
                '0' => 'pppoe name',
                '1' => 'due amount',
            ];

            // Validate the rules against each row
            $validator = Validator::make($row->toArray(), $customRules);

            // Check for validation errors
            if ($validator->fails()) {

                $errors = $validator->errors();
                $customErrors = [];
                foreach ($errors->keys() as $field) {
                    $customErrors[] = "Row $rowNumber: " . $customAttributes[$field] . ' is required <br>';
                }

                throw new \Exception(implode('', $customErrors));
            }

            if (trim($row[0])) {
                $client = Client::where('userid', trim($row[0]))->first();
            }

            $amount = trim($row[1]);

            if ($client) {

                DB::beginTransaction();

                try {
                    CustomerAccount::updateCustomrAccount($client->id, $amount, 0, 0, $amount);
                    $dueAmount = DB::table('customer_accounts')->where('client_id', $client->id)->first();
                    $client_id_time = $client->id . 'other' . '_' . now()->format('Y-m-d H:i');

                    BillGenerate::create([
                        'description'           => 'previous due',
                        'bill_amount'           => $amount,
                        'client_id'             => $client->id,
                        'billing_type'          => 'other',
                        'due_date'              => today(),
                        'due_amount'            => $dueAmount->dueAmount,
                        'parmanent_discount'    => 0,
                        'package_name'          => '',
                        'package_rate'          => '',
                        'client_id_time'        => $client_id_time,
                    ]);

                    DB::commit();
                } catch (\Throwable $th) {
                    DB::rollBack();
                }
            }
        }
    }
}
