<?php

namespace Modules\Lpj\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class KertasKerjaExport implements FromCollection, WithHeadings, WithStyles, WithColumnWidths, WithEvents
{
// use Illuminate\Contracts\View\View;
// use Maatwebsite\Excel\Concerns\FromView;
// class KertasKerjaExport implements FromView
// {

    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    // public function view(): View
    // {
    //     return view('lpj::component.kertas-kerja', [
    //         'data' => $this->data,
    //     ]);
    // }

    public function collection()
    {
        // $rows = [];

        // $nomor = 1;
        $fields = [
            'jenis_aset' => 'Jenis Aset',
            'luas_tanah' => 'Luas Tanah (M²)',
            'luas_bangunan' => 'Luas Bangunan (M²)',
            'harga' => 'Harga Transaksi/Penawaran',
            'tanggal_penawaran' => 'Tanggal Penawaran/Transaksi',
            'diskon' => 'Diskon %',
            'esitmasi_harga' => 'Esitmasi Harga Transaksi (Rp)',
            'no_telepon' => 'Telepon Contact Person',
            'nama_nara_sumbr' => 'Nama Nara Sumber',
            'status_nara_sumbr' => 'Status Nara Sumber',
            'waktu_transaksi' => 'Waktu Transaksi/Penawaran',
            'alamat' => 'Alamat Titik Gps',

            'jalan' => 'Jalan',
            'desa' => 'Desa/Kelurahan',
            'kecamatan' => 'Kecamatan',
            'kabupaten' => 'Kabupaten',
            'provinsi' => 'Provinsi',

            'jarak_pembanding' => 'Jarak Pembanding dengan Objek',
            'elevasi' => 'Estimasi Ranking Tanah',
            'peruntukan' => 'Estiamsi Rangkin Bangunan'

        ];

        $rows = [];
        $nomor = 1;

        // Add general asset information
        $rows[] = ['No.', 'Uraian', 'Objek Penilaian', 'Data Pembanding 1', 'Data Pembanding 2', 'Data Pembanding 3'];
        
        foreach ($this->data['objek'] as $key => $value) {
            $rows[] = [
                $nomor++,
                $key,
                $value,
                $this->data['pembanding1'][$key] ?? '',
                $this->data['pembanding2'][$key] ?? '',
                $this->data['pembanding3'][$key] ?? ''
            ];
        }


        // B. Perhitungan Penyesuaian
        $rows[] = [''];
        $rows[] = [''];
        $rows[] = ['B. Estimasi Nilai Tanah Pembanding dengan Teknik Penyisaan Tanah untuk mendapatkan per meter persegi estimasi Nilai Tanah Pembanding'];
        $rows[] = ['No.','Uraian', 'Objek Penilaian', 'Data Pembanding 1', 'Data Pembanding 2', 'Data Pembanding 3'];
        $nostimasi = 1;
        $filedEstimasi = [
            'estimasi' => 'Estimasi Biaya Pengganti Baru Bangunan (Rp)',
            'estimasi_spl' => 'Estimasi Biaya Pengganti Baru SPL (Rp)',
            'penyusutan' => 'Penyusutan Fisik Banguna',

            'a' =>   'a. rincian ttipe bangunan (MAPPI)',
            'b' =>   'b. umur ekonomis (MAPPI)',
            'c' => 'c. estimasi Tahun tahun visual dengan mempertimbangkan renovasi',
            'd' => 'd. Sehingga sisa umur efektif',
            'e' => 'e. kondisi bagunan',
            'f' => 'f.sehinggan penyusutan fisik',
            'penyusutan_fungsi' => 'Penyusutan fungsi Bangunan (%)',
            'penyusutan_ekonomi' => 'Penyusutan Ekonomi Bangunan (%)',
            'total_penyusutan' => 'Total Penyusutan (%)',
            'estimasi_nilai' => 'Estimasi Nilai Bangunan dan SPL (Rp)',
            'estimasi_tanah' => 'Estimasi Nilai Tanah Pembanding (Rp)',
            'estimasi_nilai' => 'Estimasi Nilai Tanah Pembanding (Rp)',
        ];

        foreach ($filedEstimasi as $key => $label) {
            $rows[] = [
                $nostimasi++,
                $label,
                $this->data['estimasi'][$key] ?? '',
                $this->data['estimasi1'][$key] ?? '',
                $this->data['estimasi2'][$key] ?? '',
                $this->data['estimasi3'][$key] ?? ''

            ];
        }


        $row[] = [''];
        $row[] = [''];
        $rows[] = ['INDIKASI NILAI TANAHATAS OBJEK PENILAIAN'];

        $indikasi=[
            'luas_tanah' => 'Luas Tanah ',
            'indikasi_per' => 'INDIKASI TANAH PER M2 (RP/M2)',
            'indikasi_total' => 'INDIKASI TANAH TOTAL(RP)',
            'varian' => 'VARIANT(%)',
        ];

        foreach ($indikasi as $key => $label) {
            $rows[] = [
                $label,
                $this->data['indikasi'][$key] ?? '',
            ];
        }


        // C. Peta Lokasi
        $rows[] = [''];
        $rows[] = [''];
        $rows[] = ['C. Peta Lokasi'];
        $rows[] = [$this->data['foto_objek']['foto_objek_peta'] ?? ''];

        // D. Foto Objek dan Data Pembanding
        $rows[] = [''];
        $rows[] = ['D. Foto Objek dan Data Pembanding'];
        $rows[] = [
            $this->data['foto_objek1']['foto_objek'] ?? '',
            $this->data['foto_objek2']['foto_objek'] ?? '',
            '', '', ''
        ];

        // E. Foto Objek
        $rows[] = [''];
        $rows[] = ['E. Foto Objek'];
        $rows[] = [
            $this->data['foto']['foto_objek'] ?? '',
            $this->data['foto']['foto_objek'] ?? '',
            '', '', ''
        ];

        return collect($rows);
    }

    public function headings(): array
    {
        return [
            ['KERTAS KERJA PENILAIAN'],
            ['Pendekatan Pasar'],
            ['Metode Perbandingan Data Pasar'],
            ['Tanggal Penilaian: ' . ($this->headerInfo['tanggal_penilaian'] ?? '')],
            ['Nama Pemilik Aset: ' . ($this->headerInfo['nama_pemilik'] ?? '')],
            ['Nama Pemberi Tugas: ' . ($this->headerInfo['nama_pemberi_tugas'] ?? '')],
            ['Lokasi: ' . ($this->headerInfo['lokasi_lengkap'] ?? '')],

        ];
    }
    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                // Styling untuk header utama
               

                // Styling untuk setiap section header
                $sectionRows = [10, 34, 56, 46, 52]; // Sesuaikan dengan posisi setiap section
                foreach ($sectionRows as $row) {
                    $event->sheet->getStyle("A{$row}:F{$row}")->getFill()
                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                        ->getStartColor()->setRGB('E2EFDA');
                }

                // Merge cells untuk headers
                $event->sheet->mergeCells('A1:E1');
                $event->sheet->mergeCells('A2:E2');
                $event->sheet->mergeCells('A4:E4');
                $event->sheet->mergeCells('A5:E5');
                $event->sheet->mergeCells('A6:E6');
                $event->sheet->mergeCells('A7:E7');
                $event->sheet->mergeCells('A8:E8');

                // Alignment
                $event->sheet->getStyle('A1:E8')->getAlignment()
                    ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
                    $this->insertImages($event->sheet);
                }
        ];
    }
    public function columnWidths(): array
    {
        return [
            'A' => 5,
            'B' => 30,
            'C' => 30,
            'D' => 30,
            'E' => 30,
            'F' => 30,
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            // Style for the main header

            // Style for section headers
            10 => ['font' => ['bold' => true]], // A. Informasi Umum
            34 => ['font' => ['bold' => true]], // B. Estimasi Nilai Tanah
            35 => ['font' => ['bold' => true]], // C. Peta Lokasi
            57 => ['font' => ['bold' => true]], // D. Foto Objek dan Pembanding
            60 => ['font' => ['bold' => true]], // E. Foto Objek

            // Default styling for columns
            'A:J' => [
                'alignment' => ['horizontal' => 'left', 'vertical' => 'center'],
                'wrapText' => true,
            ],

            // Style for other sections (like photo and map sections)

            // Style for the other headers
            'A11:F11' => [
                'font' => ['bold' => true],
                'fill' => ['fillType' => 'solid', 'color' => ['rgb' => 'E2EFDA']],
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                    ]
                ]
            ],
            'A12:F31' => [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                    ]
                ]
            ],


            'A35:F35' => [
                'font' => ['bold' => true],
                'fill' => ['fillType' => 'solid', 'color' => ['rgb' => 'E2EFDA']],
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                    ]
                ]
            ],
            'A35:F49' => [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                    ]
                ]
            ],

            // end header
        ];
    }

    
    protected function insertImages($sheet)
    {
        ini_set('max_execution_time', '300'); 

        $worksheet = $sheet->getDelegate();
    
        // Insert images for pembanding1
        if (!empty($this->data['pembanding1']['foto_objek'])) {
            $drawing = new Drawing();
            $drawing->setName('Pembanding 1');
            $drawing->setDescription('Foto Objek Pembanding 1');
            $drawing->setPath(storage_path('app/public/' . $this->data['pembanding1']['foto_objek'])); // Adjust path as needed
            $drawing->setHeight(90);
            $drawing->setCoordinates('C' . (count($this->collection()) + 2)); // Adjust coordinates as needed
            $drawing->setWorksheet($worksheet);
        }
    
        // Repeat for pembanding2 and pembanding3
        if (!empty($this->data['pembanding2']['foto_objek'])) {
            $drawing = new Drawing();
            $drawing->setName('Pembanding 2');
            $drawing->setDescription('Foto Objek Pembanding 2');
            $drawing->setPath(storage_path('app/public/' . $this->data['pembanding2']['foto_objek'])); // Adjust path as needed
            $drawing->setHeight(90);
            $drawing->setCoordinates('C' . (count($this->collection()) + 4)); // Adjust coordinates as needed
            $drawing->setWorksheet($worksheet);
        }
    
        if (!empty($this->data['pembanding3']['foto_objek'])) {
            $drawing = new Drawing();
            $drawing->setName('Pembanding 3');
            $drawing->setDescription('Foto Objek Pembanding 3');
            $drawing->setPath(storage_path('app/public/' . $this->data['pembanding3']['foto_objek'])); // Adjust path as needed
            $drawing->setHeight(90);
            $drawing->setCoordinates('C' . (count($this->collection()) + 6)); // Adjust coordinates as needed
            $drawing->setWorksheet($worksheet);
        }
    
        // Insert images for foto_objek
        foreach ($this->data['foto_objek'] as $index => $foto) {
            if (!empty($foto['foto_objek'])) {
                $drawing = new Drawing();
                $drawing->setName($foto['name_objek']);
                $drawing->setDescription($foto['deskripsi_objek']);
                $drawing->setPath(storage_path('app/public/' . $foto['foto_objek'])); // Adjust path as needed
                $drawing->setHeight(90);
                $drawing->setCoordinates('C' . (count($this->collection()) + (8 + $index * 2))); // Adjust coordinates as needed
                $drawing->setWorksheet($worksheet);
            }
        }
    }
    


}
