<?php

namespace App\Imports;

use DateTime;
use Exception;
use Throwable;
use Carbon\Carbon;
use App\Models\Nas;
use App\Models\Pop;
use App\Models\Client;
use App\Models\Packages;
use App\Models\SubPackage;
use App\Models\Clientsinfo;
use App\Models\map\TjBox;
use GuzzleHttp\Promise\Create;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use App\Models\MikcrotikClientList;
use App\Models\PON;
use App\Models\ReselleBalanceLogReport;
use Maatwebsite\Excel\Concerns\Importable;
use App\Models\SubResellerBalanceLogReport;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Facade\Ignition\Support\Packagist\Package;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ClientsImport implements ToCollection
{
    use Importable;
    public function collection(Collection $rows)
    {
        // userid wise info update

        $count = 0;
        foreach ($rows as $row) {
            $count++;
            // $list_billing_cycle = preg_replace("/[^0-9]/", "", $row[1]);
            // $int_billing_cycle = $list_billing_cycle;
            // $expire = date('2026-03-' . $int_billing_cycle . ' 00:00:00');
            // $today = Carbon::parse(today())->format('Y-m-d 00:00:00');

            // if (strtotime($expire) < strtotime($today)) {
            //     $expire = Carbon::parse($expire)->addMonth();
            // }

            if (is_numeric($row[1])) {
                $carbonDate = Carbon::parse(($row[1] - 25569) * 86400)->format('Y-m-d 00:00:00');
                $day = Carbon::parse($carbonDate)->format('d');
            } else {
                $carbonDate = Carbon::parse($row[1])->format('Y-m-d 00:00:00');
                $day = Carbon::parse($carbonDate)->format('d');
            }

            $check_client = Client::where('userid', trim($row[0]))->first();
            if ($check_client != null) {
                $check_client->billing_cycle = $day;
                if (is_numeric($row[1])) {
                    $check_client->expire_date = Carbon::parse(($row[1] - 25569) * 86400)->format('Y-m-d 00:00:00');
                } else {
                    $check_client->expire_date = Carbon::parse($row[1])->format('Y-m-d 00:00:00');
                }
                $check_client->update();


                // $clientInfo = Clientsinfo::where('client_id', $check_client->id)->first();
                // if (is_numeric($row[2])) {
                //     $clientInfo->joinDate = Carbon::parse(($row[2] - 25569) * 86400)->format('Y-m-d 00:00:00');
                // } else {
                //     if (isset($row[2])) {
                //         $clientInfo->joinDate = Carbon::parse($row[2])->format('Y-m-d 00:00:00');
                //     } else {
                //         $clientInfo->joinDate = Carbon::parse(today())->format('Y-m-d 00:00:00');
                //     }
                // }
                // $clientInfo->update();
            }
        }
    }
}
