<?php

namespace App\Imports;

use Carbon\Carbon;
use App\Models\Branch;
use App\Models\offer;
use App\Models\Fuletype;
use App\Models\Carmodel;
use App\Models\Carvarient;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithProgressBar;
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;

class ImportOffersDiscount implements ToModel, WithStartRow, SkipsOnError, SkipsOnFailure, WithProgressBar
{
    use Importable, SkipsErrors, SkipsFailures;

    public function startRow(): int
    {
        return 2;
    }

    public function model(array $row)
    {
        /* =======================
           🔹 BRANCH (MULTIPLE)
        ======================= */
        $branch_ids = null;
        if (!empty($row[6])) {
            $branchNames = array_map('trim', explode(',', $row[6]));

            $branches = Branch::whereIn('name', $branchNames)->pluck('id', 'name');

            if (count($branches) != count($branchNames)) {
                session(['error' => 'Branch not found: ' . implode(',', $branchNames)]);
                return null;
            }

            $branch_ids = implode(',', $branches->values()->toArray());
        }

        /* =======================
           🔹 VARIANT (MULTIPLE)
        ======================= */
        $variant_ids = null;
        if (!empty($row[9])) {
            $variantNames = array_map('trim', explode(',', $row[9]));

            $variants = Carvarient::whereIn('name', $variantNames)
                ->where('status', 'active')
                ->pluck('id', 'name');

            if (count($variants) != count($variantNames)) {
                session(['error' => 'Variant not found: ' . implode(',', $variantNames)]);
                return null;
            }

            $variant_ids = implode(',', $variants->values()->toArray());
        }

        /* =======================
           🔹 CAR MODEL
        ======================= */
        $model_id = null;
        if (!empty($row[7])) {
            $model = Carmodel::where('name', $row[7])
                ->where('status', 'active')
                ->first();

            if (!$model) {
                session(['error' => 'Car Model not found: ' . $row[7]]);
                return null;
            }

            $model_id = $model->id;
        }

        /* =======================
           🔹 FUEL TYPE
        ======================= */
        $fuel_id = null;
        if (!empty($row[8])) {
            $fuel = Fuletype::where('title', $row[8])->first();

            if (!$fuel) {
                session(['error' => 'Fuel type not found: ' . $row[8]]);
                return null;
            }

            $fuel_id = $fuel->id;
        }

        /* =======================
           🔹 DATE FORMAT (IMPORTANT)
        ======================= */
        $start_date = $this->formatDate($row[1]);
        $end_date   = $this->formatDate($row[2]);

        /* =======================
           🔹 FINAL DATA
        ======================= */
        $data = [
            'title' => $row[0],
            'start_date' => $start_date,
            'end_date' => $end_date,
            'offer_type' => $row[3],
            'amount' => $row[4],
            'company_contribution' => $row[5],

            'fk_branch_id' => $branch_ids,
            'fk_car_model_id' => $model_id,
            'fk_fuel_id' => $fuel_id,
            'fk_car_varient_id' => $variant_ids,

            'vin_number' => $row[10], // store as-is
            'description' => $row[11],

            'status' => 'active',
            'created_at' => now(),
            'created_by' => Auth::id(),
            'updated_at' => now(),
            'updated_by' => Auth::id(),
        ];

        return offer::create($data);
    }

    /* ==========================================
       🔥 UNIVERSAL DATE FORMAT FUNCTION
    ========================================== */
    private function formatDate($date)
    {
        try {
            if (empty($date)) {
                return null;
            }

            // ✅ Excel numeric date (VERY COMMON)
            if (is_numeric($date)) {
                return Carbon::instance(
                    ExcelDate::excelToDateTimeObject($date)
                )->format('Y-m-d');
            }

            // ✅ Try multiple formats
            $formats = [
                'd-m-Y',
                'd/m/Y',
                'Y-m-d',
                'm/d/Y',
                'd-m-Y H:i:s',
                'd/m/Y H:i:s'
            ];

            foreach ($formats as $format) {
                try {
                    return Carbon::createFromFormat($format, $date)->format('Y-m-d');
                } catch (\Exception $e) {
                    continue;
                }
            }

            // ✅ Fallback (auto parse)
            return Carbon::parse($date)->format('Y-m-d');

        } catch (\Exception $e) {
            return null;
        }
    }
}