<?php

namespace Modules\Lpj\Exports;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Illuminate\Database\Eloquent\Builder;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Modules\Lpj\Models\Debiture;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Helpers\Lpj;

class LaporanPenilaiJaminanExport implements FromQuery, WithHeadings, WithMapping, ShouldAutoSize
{
    protected $tanggalAwal;
    protected $tanggalAkhir;
    protected $status;
    protected $selectedIds;

    public function __construct($tanggalAwal = null, $tanggalAkhir = null, $status = null, $selectedIds = null)
    {
        $this->tanggalAwal = $tanggalAwal;
        $this->tanggalAkhir = $tanggalAkhir;
        $this->status = $status;
        $this->selectedIds = $selectedIds;
    }


    public function query()
    {
        $query = Permohonan::query()
            ->with(['user', 'debiture', 'branch', 'tujuanPenilaian', 'penilaian', 'dokumenjaminan.jenisJaminan','nilaiPlafond', 'penilai', 'inspeksi']);

        // Filter by date range if provided
        if ($this->tanggalAwal && $this->tanggalAkhir) {
            $query->whereBetween('tanggal_permohonan', [$this->tanggalAwal, $this->tanggalAkhir]);
        }

        $query->where('status', 'done');
        // Filter by status if provided
        if ($this->status) {
            $types = is_array($this->status) ? $this->status : [$this->status];
            $types = array_map('strtolower', $types);
            $query->whereHas('penilai', function (Builder $query) use ($types) {
                $query->whereIn('type_penilai', $types);
            });
        }


        // Filter by selected IDs if provided
        if ($this->selectedIds) {
            $selectedIds = is_array($this->selectedIds) ? $this->selectedIds : explode(',', $this->selectedIds);
            $query->whereIn('id', $selectedIds);
        }

        return $query;
    }


    public function map($row): array
    {

        // ambil data alamat dari inspeksi
        $alamat_inspeksi = null;

        if ($row->inspeksi) {
            $alamat_inspeksi = json_decode($row->inspeksi->data_form, true) ?? null;
            $alamat_inspeksi = $alamat_inspeksi['asset']['alamat']['sesuai'] ?? $alamat_inspeksi['asset']['alamat']['tidak sesuai'] ?? [];
        }
        $alamat_inspeksi = $alamat_inspeksi['address'] ?? '-';


        // ambil data dari table penilai
        $fieldPenilai = ['lpj', 'resume', 'memo', 'rap', 'call-report'];
        $penilaiCek = null;

        // Cari field yang tersedia
        foreach ($fieldPenilai as $value) {
            if (!empty($row->penilai->$value)) {
                $penilaiCek = $row->penilai->$value;
                break;
            }
        }

        $decodePenilai = json_decode($penilaiCek, true) ?? [];
        // Ambil nilai utama
        $luasTanah = $decodePenilai['luas_tanah'] ?? 0;
        $nilaiTanah1 = $decodePenilai['nilai_tanah_1'] ?? 0;
        $luasBangunan = $decodePenilai['luas_bangunan'] ?? 0;
        $nilaiBangunan1 = $decodePenilai['nilai_bangunan_1'] ?? 0;
        $totalNilaiPasar = $decodePenilai['total_nilai_pasar_wajar'] ?? 0;
        $likuidasi = $decodePenilai['likuidasi'] ?? 0;

        // Ambil data npw_tambahan jika ada
        $npwTambahan = $decodePenilai['npw_tambahan'] ?? [];
        $tambahanDetails = [];
        foreach ($npwTambahan as $tambahan) {
            $tambahanDetails[] = sprintf(
                '%s: Luas: %s, Nilai 1: %s, Nilai 2: %s',
                $tambahan['name'] ?? '-',
                $tambahan['luas'] ?? 0,
                $tambahan['nilai_1'] ?? 0,
                $tambahan['nilai_2'] ?? 0
            );
        }
        $tambahanSummary = implode("; ", $tambahanDetails);

        // Ambil data penilaian dari table penilaian
        $user_penilai =  $row->penilaian->userPenilai ?? null;
        $user_penilai_name = null;
        foreach ($user_penilai as $value) {
            if ($value->role == 'penilai') {
                $user_penilai_name = $value->user->name;
                $nik_penilai = $value->user->nik ?? '-';
                break;
            }
        }


        return [
            $row->id,
            $row->nomor_registrasi,
            $row->user->name,
            $row->branch->name,
            $row->tujuanPenilaian->name,
            $row->debiture->name,
            $row->penilai->type_penilai ?? '-',
            $alamat_inspeksi ?? '-',
            $luasTanah,
            $luasBangunan,
            $nilaiTanah1,
            $nilaiBangunan1,
            $totalNilaiPasar,
            $likuidasi,
            $row->laporan->created_at ?? '-',
            $user_penilai_name,
            $nik_penilai,
            $row->created_at,
        ];
    }


    public function headings(): array
    {
        return [
            'ID',
            'Nomor Registrasi',
            'User Pemohon',
            'Cabang',
            'Tujuan Penilaian',
            'Debitur',
            'Jenis Laporan',
            'Lokasi Jaminan',
            'Luas Tanah',
            'Luas Bangunan',
            'Harga Tanah',
            'Harga Bangunan',
            'Nilai Pasar Wajar',
            'Likuidasi',
            'Tanggal Laporan',
            'Nama Penilai',
            'Nik Penilai',
            'Created At',
        ];
    }
    public function columnFormats(): array
    {
        return [
            'A' => NumberFormat::FORMAT_NUMBER,
            'C' => NumberFormat::FORMAT_DATE_DATETIME,
            'K' => NumberFormat::FORMAT_DATE_DATETIME,
            'N' => NumberFormat::FORMAT_DATE_DATETIME
        ];
    }
}
