<?php

namespace Modules\Lpj\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Lpj\Models\LaporanSlik;
use Modules\Lpj\Models\Slik;
use Modules\Lpj\Exports\LaporanSlikExport;

class LaporanSlikController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::laporan-slik.index');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'slik_id' => 'required|exists:sliks,id'
            ]);

            $slik = Slik::findOrFail($request->slik_id);

            // Cek apakah data sudah ada di laporan_slik
            $existing = LaporanSlik::where('slik_id', $slik->id)->first();
            if ($existing) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data sudah ada di laporan SLIK'
                ], 422);
            }

            // Copy data dari tabel slik ke laporan_slik
            $laporanSlik = LaporanSlik::create([
                'slik_id' => $slik->id,
                'sandi_bank' => $slik->sandi_bank,
                'kode_kantor' => $slik->kode_kantor,
                'kode_cabang' => $slik->kode_cabang,
                'tahun' => $slik->tahun,
                'bulan' => $slik->bulan,
                'no_rekening' => $slik->no_rekening,
                'cif' => $slik->cif,
                'kode_jenis' => $slik->kode_jenis,
                'kode_jenis_ket' => $slik->kode_jenis_ket,
                'kode_sifat' => $slik->kode_sifat,
                'kode_sifat_ket' => $slik->kode_sifat_ket,
                'kode_valuta' => $slik->kode_valuta,
                'kode_valuta_ket' => $slik->kode_valuta_ket,
                'baki_debet' => $slik->baki_debet,
                'kolektibilitas' => $slik->kolektibilitas,
                'kolektibilitas_ket' => $slik->kolektibilitas_ket,
                'tanggal_mulai' => $slik->tanggal_mulai,
                'tanggal_jatuh_tempo' => $slik->tanggal_jatuh_tempo,
                'tanggal_selesai' => $slik->tanggal_selesai,
                'tanggal_restrukturisasi' => $slik->tanggal_restrukturisasi,
                'kode_sebab_macet' => $slik->kode_sebab_macet,
                'kode_sebab_macet_ket' => $slik->kode_sebab_macet_ket,
                'tanggal_macet' => $slik->tanggal_macet,
                'kode_kondisi' => $slik->kode_kondisi,
                'kode_kondisi_ket' => $slik->kode_kondisi_ket,
                'tanggal_kondisi' => $slik->tanggal_kondisi,
                'nilai_agunan' => $slik->nilai_agunan,
                'nilai_agunan_ket' => $slik->nilai_agunan_ket,
                'jenis_agunan' => $slik->jenis_agunan,
                'kode_agunan' => $slik->kode_agunan,
                'kode_agunan_ket' => $slik->kode_agunan_ket,
                'peringkat_agunan' => $slik->peringkat_agunan,
                'peringkat_agunan_ket' => $slik->peringkat_agunan_ket,
                'nama_debitur' => $slik->nama_debitur,
                'npwp' => $slik->npwp,
                'no_ktp' => $slik->no_ktp,
                'no_telp' => $slik->no_telp,
                'kode_kab_kota' => $slik->kode_kab_kota,
                'kode_kab_kota_ket' => $slik->kode_kab_kota_ket,
                'kode_negara_domisili' => $slik->kode_negara_domisili,
                'kode_negara_domisili_ket' => $slik->kode_negara_domisili_ket,
                'kode_pos' => $slik->kode_pos,
                'alamat' => $slik->alamat,
                'fasilitas' => $slik->fasilitas,
                'status_agunan' => $slik->status_agunan,
                'tanggal_lapor' => $slik->tanggal_lapor,
                'status' => 'active',
                'created_by' => auth()->id(),
                'updated_by' => auth()->id(),
            ]);

            // Hapus data dari tabel slik setelah berhasil dipindahkan
            $slik->delete();

            return response()->json([
                'success' => true,
                'message' => 'Data berhasil dipindahkan ke laporan SLIK',
                'data' => $laporanSlik
            ]);

        } catch (\Exception $e) {
            Log::error('Error moving SLIK to laporan: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat memindahkan data'
            ], 500);
        }
    }

    /**
     * Data untuk datatables dengan server-side processing
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function dataForDatatables(Request $request)
    {
        try {
            // Retrieve data from the database
            $query = LaporanSlik::query();

            // Apply search filter if provided
            if ($request->has('search') && !empty($request->get('search'))) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->where('sandi_bank', 'LIKE', "%$search%")
                      ->orWhere('no_rekening', 'LIKE', "%$search%")
                      ->orWhere('cif', 'LIKE', "%$search%")
                      ->orWhere('nama_debitur', 'LIKE', "%$search%")
                      ->orWhere('fasilitas', 'LIKE', "%$search%")
                      ->orWhere('status_agunan', 'LIKE', "%$search%");
                });
            }

            // Apply year filter
            if ($request->has('year') && !empty($request->get('year'))) {
                $query->where('tahun', $request->get('year'));
            }

            // Apply month filter
            if ($request->has('month') && !empty($request->get('month'))) {
                $query->where('bulan', $request->get('month'));
            }

            // Apply sandi bank filter
            if ($request->has('sandi_bank') && !empty($request->get('sandi_bank'))) {
                $query->where('sandi_bank', $request->get('sandi_bank'));
            }

            // Apply kolektibilitas filter
            if ($request->has('kolektibilitas') && !empty($request->get('kolektibilitas'))) {
                $query->where('kolektibilitas', $request->get('kolektibilitas'));
            }

            // Apply status filter
            if ($request->has('status') && !empty($request->get('status'))) {
                $query->where('status', $request->get('status'));
            }

            // Apply sorting if provided
            if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
                $order  = $request->get('sortOrder');
                $column = $request->get('sortField', 'created_at');
                $query->orderBy($column, $order);
            } else {
                $query->orderBy('created_at', 'desc');
            }

            // Get the total count of records
            $totalRecords = $query->count();

            // Apply pagination if provided
            if ($request->has('page') && $request->has('size')) {
                $page   = $request->get('page');
                $size   = $request->get('size');
                $offset = ($page - 1) * $size;    // Calculate the offset

                $query->skip($offset)->take($size);
            }

            // Get the filtered count of records
            $filteredRecords = $query->count();

            // Get the data for the current page
            $data = $query->get();

            // Transform data untuk datatables
            $transformedData = $data->map(function ($item) {
                return [
                    'id'                     => $item->id,
                    'sandi_bank'             => $item->sandi_bank,
                    'tahun'                  => $item->tahun,
                    'bulan'                  => $item->bulan,
                    'no_rekening'            => $item->no_rekening,
                    'cif'                    => $item->cif,
                    'nama_debitur'           => $item->nama_debitur,
                    'kolektibilitas'         => $item->kolektibilitas,
                    'kolektibilitas_badge'   => $item->kolektibilitas_badge ?? '',
                    'fasilitas'              => $item->fasilitas,
                    'nilai_agunan'           => $item->nilai_agunan_formatted ?? '',
                    'status_agunan'          => $item->status_agunan,
                    'status_badge'           => $item->status_badge ?? '',
                    'created_by'             => $item->creator?->name ?? '-',
                    'created_at'             => dateFormat($item->created_at, true) ?? $item->created_at->format('d/m/Y H:i')
                ];
            });

            // Calculate the page count
            $pageCount = ceil($totalRecords / ($request->get('size', 10)));

            // Calculate the current page number
            $currentPage = $request->get('page', 1);

            // Return the response data as a JSON object
            return response()->json([
                'draw'            => $request->get('draw'),
                'recordsTotal'    => $totalRecords,
                'recordsFiltered' => $filteredRecords,
                'pageCount'       => $pageCount,
                'page'            => $currentPage,
                'totalCount'      => $totalRecords,
                'data'            => $transformedData,
            ]);

        } catch (\Exception $e) {
            Log::error('Error in laporan slik datatables: ' . $e->getMessage());

            return response()->json([
                'draw'            => $request->get('draw'),
                'recordsTotal'    => 0,
                'recordsFiltered' => 0,
                'pageCount'       => 0,
                'page'            => 1,
                'totalCount'      => 0,
                'data'            => [],
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        try {
            $laporanSlik = LaporanSlik::findOrFail($id);
            return view('lpj::laporan-slik.show', compact('laporanSlik'));
        } catch (\Exception $e) {
            Log::error('Error showing laporan slik: ' . $e->getMessage());
            return back()->with('error', 'Data tidak ditemukan');
        }
    }

    /**
     * Export laporan SLIK to Excel
     */
    public function export(Request $request)
    {
        try {
            $query = LaporanSlik::query();

            // Apply filters
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function($q) use ($search) {
                    $q->where('nama_debitur', 'like', "%{$search}%")
                      ->orWhere('no_rekening', 'like', "%{$search}%")
                      ->orWhere('cif', 'like', "%{$search}%");
                });
            }

            if ($request->has('year') && $request->year) {
                $query->where('tahun', $request->year);
            }

            if ($request->has('month') && $request->month) {
                $query->where('bulan', $request->month);
            }

            if ($request->has('status') && $request->status) {
                $query->where('status', $request->status);
            }

            $filename = 'laporan-slik-' . now()->format('Y-m-d-His') . '.xlsx';

            return Excel::download(new LaporanSlikExport($query), $filename);

        } catch (\Exception $e) {
            Log::error('Error exporting laporan slik: ' . $e->getMessage());
            return back()->with('error', 'Gagal export data: ' . $e->getMessage());
        }
    }
}
