<?php

namespace App\Http\Controllers\Imports;

use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Imports\Services\GenericImport;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\PermitsReminder;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ImportPermitsReminderController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request)
    {
        $object = new DocumentObject('', $request->input('files'), '', ApprovalStatus::APPROVED, 'imports');
        $file = json_decode($object->getFiles()[0])->file_info->original->file;
        $file = storage_path('app/documents/' . $file);

        $import = new GenericImport();
        Excel::import($import, $file);
        $excelRows = $import->rows->toArray();
        $successRows = [];
        $returnArray = []; // Initialize the return array

        foreach ($excelRows as $row) {
            if (is_null($row['expiry_date']) && is_null($row['reminder_date'])) {
                continue;
            }

            $row['expiry_date'] = $this->changeExcelDate($row['expiry_date']);
            $row['reminder_date'] = $this->changeExcelDate($row['reminder_date']);

            $validator = Validator::make($row, [
                'model' => 'required|unique:permits_reminders,model',
                'expiry_date' => 'required|date|after_or_equal:today',
                'reminder_date' => 'required|date|after_or_equal:today',
            ]);

            if ($validator->fails()) {
                $row['status'] = 'failed';
                $row['message'] = $validator->errors()->all();

                $returnArray[] = $row;
            } else {
                $row['created_at'] = Carbon::now();
                $row['updated_at'] = Carbon::now();
                $successRows[] = $row;
            }
        }

        if (!empty($successRows)) {
            PermitsReminder::insert($successRows); // Insert only if there are successful rows
        }

        $successCount = count($successRows);

        return response()->json([
            'completedRows' => $successCount,
            'failedRows' => count($returnArray),
            'remark' => "Successful Imported {$successCount} data.",
            'data' => $returnArray
        ]);
    }

    public function changeExcelDate($date)
    {
        $formatedDate = DateTime::createFromFormat('d/m/Y', $date);
        if ($formatedDate instanceof DateTime) {
            return $formatedDate->format('Y-m-d');
        }

        $unixTime = (($date - 25569) * 86400);

        return (new DateTime("@$unixTime"))->format('Y-m-d');
    }
}
