<?php

namespace Modules\Lpj\Http\Controllers;

use Throwable;
use Illuminate\Http\Request;
use Modules\Lpj\Models\KJPP;
use Modules\Location\Models\City;
use Modules\Lpj\Models\IjinUsaha;
use Modules\Lpj\Exports\KJPPExport;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Location\Models\Village;
use Modules\Lpj\Models\JenisJaminan;
use Modules\Location\Models\District;
use Modules\Location\Models\Province;
use Illuminate\Support\Facades\Storage;
use Modules\Lpj\Http\Requests\KJPPRequest;

class KJPPController extends Controller
{
    public $user;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::kjpp.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $ijin_usaha = IjinUsaha::all();
        $jenis_aset = JenisJaminan::all();
        $provinces = Province::all();

        // Generate KJPP Number
        $lastKjpp = KJPP::orderBy('code', 'desc')->first();
        $nextNumber = $lastKjpp ? intval(substr($lastKjpp->code, 1, 6)) + 1 : 1;
        $kjppNumber = 'K' . str_pad($nextNumber, 6, '0', STR_PAD_LEFT);

        // Combine KJPP number with branch code
        $fullKjppNumber = $kjppNumber;
        $detailJoinEmailKantor = json_encode([]);
        $detailJoinPimpinan = json_encode([]);
        $detailJoinPicReviewer = json_encode([]);
        $detailJoinPicAdmin = json_encode([]);
        $detailJoinPicMarketing = json_encode([]);

        return view('lpj::kjpp.create', compact('ijin_usaha', 'jenis_aset', 'provinces', 'fullKjppNumber', 'detailJoinEmailKantor', 'detailJoinPimpinan', 'detailJoinPicReviewer', 'detailJoinPicAdmin', 'detailJoinPicMarketing'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(KJPPRequest $request)
    {
        $validated = $request->validated();


        if ($validated) {
            $detailEmailKantor = [];
            $detailNamaPimpinan = [];
            $detailNomorPicPimpinan = [];
            $detailNamaPicReviewer = [];
            $detailNomorHpPicReviewer = [];
            $detailNamaPicAdmin = [];
            $detailNomorHpPicAdmin = [];
            $detailNamaPicMarketing = [];
            $detailNomorHpPicMarketing = [];

            $emailKantor = $request->input('detail_email_kantor.email_kantor', []);
            $namaPimpinan = $request->input('detail_nama_pimpinan.nama_pimpinan', []);
            $nomorHpPimpinan = $request->input('detail_nomor_hp_pimpinan.nomor_hp_pimpinan', []);
            $namaPicReviewer = $request->input('detail_nama_pic_reviewer.nama_pic_reviewer', []);
            $nomorHpPicReviewer = $request->input('detail_nomor_hp_pic_reviewer.nomor_hp_pic_reviewer', []);
            $namaPicAdmin = $request->input('detail_nama_pic_admin.nama_pic_admin', []);
            $nomorHpPicAdmin = $request->input('detail_nomor_hp_pic_admin.nomor_hp_pic_admin', []);
            $namaPicMarketing = $request->input('detail_nama_pic_marketing.nama_pic_marketing', []);
            $nomorHpPicMarketing = $request->input('detail_nomor_hp_pic_marketing.nomor_hp_pic_marketing', []);

            foreach ($emailKantor as $value) {
                $detailEmailKantor[] = $value;
            }
            // Encode to JSON and store
            $detailEmailKantorJson = json_encode($detailEmailKantor);

            // Process detail_nama_pimpinan
            foreach ($namaPimpinan as $value) {
                $detailNamaPimpinan[] = $value;
            }
            $detailNamaPimpinanJson = json_encode($detailNamaPimpinan);

            // Process detail_nomor_pic_pimpinan
            foreach ($nomorHpPimpinan as $value) {
                $detailNomorPicPimpinan[] = $value;
            }
            $detailNomorPicPimpinanJson = json_encode($detailNomorPicPimpinan);

            // Process detail_nama_pic_reviewer
            foreach ($namaPicReviewer as $value) {
                $detailNamaPicReviewer[] = $value;
            }
            $detailNamaPicReviewerJson = json_encode($detailNamaPicReviewer);

            // Process detail_nomor_hp_pic_reviewer
            foreach ($nomorHpPicReviewer as $value) {
                $detailNomorHpPicReviewer[] = $value;
            }
            $detailNomorHpPicReviewerJson = json_encode($detailNomorHpPicReviewer);

            // Process detail_nama_pic_admin
            foreach ($namaPicAdmin as $value) {
                $detailNamaPicAdmin[] = $value;
            }
            $detailNamaPicAdminJson = json_encode($detailNamaPicAdmin);

            // Process detail_nomor_hp_pic_admin
            foreach ($nomorHpPicAdmin as $value) {
                $detailNomorHpPicAdmin[] = $value;
            }
            $detailNomorHpPicAdminJson = json_encode($detailNomorHpPicAdmin);

            // Process detail_nama_pic_marketing
            foreach ($namaPicMarketing as $value) {
                $detailNamaPicMarketing[] = $value;
            }
            $detailNamaPicMarketingJson = json_encode($detailNamaPicMarketing);

            // Process detail_nomor_hp_pic_marketing
            foreach ($nomorHpPicMarketing as $value) {
                $detailNomorHpPicMarketing[] = $value;
            }
            $detailNomorHpPicMarketingJson = json_encode($detailNomorHpPicMarketing);


            $file = $request->file('attachment');
            $filename = $file ? time() . '.' . $file->getClientOriginalExtension() : 'default.pdf';

            if ($file) {
                // Simpan file yang diunggah
                $file->storeAs('public/uploads_pdf', $filename);
            } else {
                // Salin file default ke lokasi yang diinginkan
                Storage::copy('public/test/default.pdf', 'public/uploads_pdf/' . $filename);
            }

            $validated['detail_email_kantor'] = $detailEmailKantorJson;
            $validated['detail_nama_pimpinan'] = $detailNamaPimpinanJson;
            $validated['detail_nomor_hp_pimpinan'] = $detailNomorPicPimpinanJson;
            $validated['detail_nama_pic_reviewer'] = $detailNamaPicReviewerJson;
            $validated['detail_nomor_hp_pic_reviewer'] = $detailNomorHpPicReviewerJson;
            $validated['detail_nama_pic_admin'] = $detailNamaPicAdminJson;
            $validated['detail_nomor_hp_pic_admin'] = $detailNomorHpPicAdminJson;
            $validated['detail_nama_pic_marketing'] = $detailNamaPicMarketingJson;
            $validated['detail_nomor_hp_pic_marketing'] = $detailNomorHpPicMarketingJson;
            $validated['ijin_usaha_id'] = json_encode($validated['ijin_usaha_id']);
            if (empty($validated['jenis_aset_id'])) {
                $validated['jenis_aset_id'] = json_encode([]);
            } else {
                $validated['jenis_aset_id'] = json_encode($validated['jenis_aset_id']);
            }
            // Tambahkan nama file ke data yang divalidasi
            $validated['attachment'] = $filename;

            // dd($validated);

            // Simpan data ke database
            KJPP::create($validated);

            return redirect()
                ->route('basicdata.kjpp.index')
                ->with('success', 'KJPP created successfully');
        } else {
            return redirect()
                ->route('basicdata.kjpp.create')
                ->with('error', 'Validation failed');
        }
    }

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        $kjpp = KJPP::find($id);
        $ijin_usaha = IjinUsaha::where('code', $kjpp->nomor_ijin_usaha)->get();
        $ijin_usahas = IjinUsaha::all();
        $jenis_jaminan = JenisJaminan::all();
        $provinces = Province::where('code', $kjpp->province_code)->get();
        $cities = City::where('code', $kjpp->city_code)->get();
        $districts = District::where('code', $kjpp->district_code)->get();
        $villages  = Village::where('code', $kjpp->village_code)->get();
        $detailEmailKantor = json_decode($kjpp->detail_email_kantor);
        $detailNamaPimpinan = json_decode($kjpp->detail_nama_pimpinan);
        $detailNomorHpPimpinan = json_decode($kjpp->detail_nomor_hp_pimpinan);
        $detailNamaPicReviewer = json_decode($kjpp->detail_nama_pic_reviewer);
        $detailNomorHpPicReviewer = json_decode($kjpp->detail_nomor_hp_pic_reviewer);
        $detailNamaPicAdmin = json_decode($kjpp->detail_nama_pic_admin);
        $detailNomorHpPicAdmin = json_decode($kjpp->detail_nomor_hp_pic_admin);
        $detailNamaPicMarketing = json_decode($kjpp->detail_nama_pic_marketing);
        $detailNomorHpPicMarketing = json_decode($kjpp->detail_nomor_hp_pic_marketing);

        $detailJoinEmailKantor = json_encode(array_map(function ($email) {
            return [
                'email_kantor' => $email
            ];
        }, $detailEmailKantor));

        $detailJoinPimpinan = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pimpinan'     => $nama,
                'nomor_hp_pimpinan' => $nomor
            ];
        }, $detailNamaPimpinan, $detailNomorHpPimpinan));


        $detailJoinPicReviewer = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_reviewer' => $nama,
                'nomor_hp_pic_reviewer' => $nomor
            ];
        }, $detailNamaPicReviewer, $detailNomorHpPicReviewer));

        $detailJoinPicAdmin = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_admin' => $nama,
                'nomor_hp_pic_admin' => $nomor
            ];
        }, $detailNamaPicAdmin, $detailNomorHpPicAdmin));

        $detailJoinPicMarketing = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_marketing' => $nama,
                'nomor_hp_pic_marketing' => $nomor
            ];
        }, $detailNamaPicMarketing, $detailNomorHpPicMarketing));

        return view('lpj::kjpp.show', compact('jenis_jaminan', 'ijin_usahas', 'ijin_usaha', 'kjpp', 'provinces', 'cities', 'districts', 'villages', 'detailJoinEmailKantor', 'detailJoinPicReviewer', 'detailJoinPicAdmin', 'detailJoinPicMarketing', 'detailJoinPimpinan'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $kjpp = KJPP::find($id);
        $ijin_usaha = IjinUsaha::all();
        $jenis_aset = JenisJaminan::all();
        $provinces = Province::all();
        $cities = City::where('province_code', $kjpp->province_code)->get();
        $districts = District::where('city_code', $kjpp->city_code)->get();
        $villages  = Village::where('district_code', $kjpp->district_code)->get();
        $detailEmailKantor = json_decode($kjpp->detail_email_kantor);
        $detailNamaPimpinan = json_decode($kjpp->detail_nama_pimpinan);
        $detailNomorHpPimpinan = json_decode($kjpp->detail_nomor_hp_pimpinan);
        $detailNamaPicReviewer = json_decode($kjpp->detail_nama_pic_reviewer);
        $detailNomorHpPicReviewer = json_decode($kjpp->detail_nomor_hp_pic_reviewer);
        $detailNamaPicAdmin = json_decode($kjpp->detail_nama_pic_admin);
        $detailNomorHpPicAdmin = json_decode($kjpp->detail_nomor_hp_pic_admin);
        $detailNamaPicMarketing = json_decode($kjpp->detail_nama_pic_marketing);
        $detailNomorHpPicMarketing = json_decode($kjpp->detail_nomor_hp_pic_marketing);

        $detailJoinEmailKantor = json_encode(array_map(function ($email) {
            return [
                'email_kantor' => $email
            ];
        }, $detailEmailKantor));

        $detailJoinPimpinan = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pimpinan'     => $nama,
                'nomor_hp_pimpinan' => $nomor
            ];
        }, $detailNamaPimpinan, $detailNomorHpPimpinan));


        $detailJoinPicReviewer = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_reviewer' => $nama,
                'nomor_hp_pic_reviewer' => $nomor
            ];
        }, $detailNamaPicReviewer, $detailNomorHpPicReviewer));

        $detailJoinPicAdmin = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_admin' => $nama,
                'nomor_hp_pic_admin' => $nomor
            ];
        }, $detailNamaPicAdmin, $detailNomorHpPicAdmin));

        $detailJoinPicMarketing = json_encode(array_map(function ($nama, $nomor) {
            return [
                'nama_pic_marketing' => $nama,
                'nomor_hp_pic_marketing' => $nomor
            ];
        }, $detailNamaPicMarketing, $detailNomorHpPicMarketing));

        return view('lpj::kjpp.create', compact('kjpp', 'ijin_usaha', 'jenis_aset', 'provinces', 'cities', 'districts', 'villages', 'detailJoinPicReviewer', 'detailJoinPicAdmin', 'detailJoinPicMarketing', 'detailJoinEmailKantor', 'detailJoinPimpinan'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(KJPPRequest $request, $id)
    {
        $validated = $request->validated();

        // dd($validated);

        if ($validated) {
            $detailEmailKantor = [];
            $detailNamaPimpinan = [];
            $detailNomorHpPimpinan = [];
            $detailNamaPicReviewer = [];
            $detailNomorHpPicReviewer = [];
            $detailNamaPicAdmin = [];
            $detailNomorHpPicAdmin = [];
            $detailNamaPicMarketing = [];
            $detailNomorHpPicMarketing = [];

            $emailKantor = $request->input('detail_email_kantor.email_kantor', []);
            $namaPimpinan = $request->input('detail_nama_pimpinan.nama_pimpinan', []);
            $nomorHpPimpinan = $request->input('detail_nomor_hp_pimpinan.nomor_hp_pimpinan', []);
            $namaPicReviewer = $request->input('detail_nama_pic_reviewer.nama_pic_reviewer', []);
            $nomorHpPicReviewer = $request->input('detail_nomor_hp_pic_reviewer.nomor_hp_pic_reviewer', []);
            $namaPicAdmin = $request->input('detail_nama_pic_admin.nama_pic_admin', []);
            $nomorHpPicAdmin = $request->input('detail_nomor_hp_pic_admin.nomor_hp_pic_admin', []);
            $namaPicMarketing = $request->input('detail_nama_pic_marketing.nama_pic_marketing', []);
            $nomorHpPicMarketing = $request->input('detail_nomor_hp_pic_marketing.nomor_hp_pic_marketing', []);

            foreach ($emailKantor as $value) {
                $detailEmailKantor[] = $value;
            }
            // Encode to JSON and store
            $detailEmailKantorJson = json_encode($detailEmailKantor);

            // Process detail_nama_pimpinan
            foreach ($namaPimpinan as $value) {
                $detailNamaPimpinan[] = $value;
            }
            $detailNamaPimpinanJson = json_encode($detailNamaPimpinan);

            // Process detail_nomor_hp_pimpinan
            foreach ($nomorHpPimpinan as $value) {
                $detailNomorHpPimpinan[] = $value;
            }
            $detailNomorHpPimpinanJson = json_encode($detailNomorHpPimpinan);

            // Process detail_nama_pic_reviewer
            foreach ($namaPicReviewer as $value) {
                $detailNamaPicReviewer[] = $value;
            }
            $detailNamaPicReviewerJson = json_encode($detailNamaPicReviewer);

            // Process detail_nomor_hp_pic_reviewer
            foreach ($nomorHpPicReviewer as $value) {
                $detailNomorHpPicReviewer[] = $value;
            }
            $detailNomorHpPicReviewerJson = json_encode($detailNomorHpPicReviewer);

            // Process detail_nama_pic_admin
            foreach ($namaPicAdmin as $value) {
                $detailNamaPicAdmin[] = $value;
            }
            $detailNamaPicAdminJson = json_encode($detailNamaPicAdmin);

            // Process detail_nomor_hp_pic_admin
            foreach ($nomorHpPicAdmin as $value) {
                $detailNomorHpPicAdmin[] = $value;
            }
            $detailNomorHpPicAdminJson = json_encode($detailNomorHpPicAdmin);

            // Process detail_nama_pic_marketing
            foreach ($namaPicMarketing as $value) {
                $detailNamaPicMarketing[] = $value;
            }
            $detailNamaPicMarketingJson = json_encode($detailNamaPicMarketing);

            // Process detail_nomor_hp_pic_marketing
            foreach ($nomorHpPicMarketing as $value) {
                $detailNomorHpPicMarketing[] = $value;
            }
            $detailNomorHpPicMarketingJson = json_encode($detailNomorHpPicMarketing);


            $file = $request->file('attachment');
            $filename = $file ? time() . '.' . $file->getClientOriginalExtension() : null;

            if ($file !== null) {
                // Jika ada file dari database maka hapus file yang lama ke file yang baru
                $kjpp = KJPP::find($id);
                // Jika filenya ada default.pdf jangan dihapus
                if ($kjpp->attachment !== 'default.pdf') {
                    Storage::delete('public/uploads_pdf/' . $kjpp->attachment);
                }
                // Simpan file yang diunggah
                $file->storeAs('public/uploads_pdf', $filename);
                $validated['attachment'] = $filename;
            } else {
                // Jika tidak ada file yang diunggah, gunakan file yang sudah ada atau file default
                $kjpp = KJPP::find($id);
                $validated['attachment'] = $kjpp->attachment ?? 'default.pdf';
            }

            $validated['detail_email_kantor'] = $detailEmailKantorJson;
            $validated['detail_nama_pimpinan'] = $detailNamaPimpinanJson;
            $validated['detail_nomor_hp_pimpinan'] = $detailNomorHpPimpinanJson;
            $validated['detail_nama_pic_reviewer'] = $detailNamaPicReviewerJson;
            $validated['detail_nomor_hp_pic_reviewer'] = $detailNomorHpPicReviewerJson;
            $validated['detail_nama_pic_admin'] = $detailNamaPicAdminJson;
            $validated['detail_nomor_hp_pic_admin'] = $detailNomorHpPicAdminJson;
            $validated['detail_nama_pic_marketing'] = $detailNamaPicMarketingJson;
            $validated['detail_nomor_hp_pic_marketing'] = $detailNomorHpPicMarketingJson;
            $validated['ijin_usaha_id'] = json_encode($validated['ijin_usaha_id']);
            if (empty($validated['jenis_aset_id'])) {
                $validated['jenis_aset_id'] = json_encode([]);
            } else {
                $validated['jenis_aset_id'] = json_encode($validated['jenis_aset_id']);
            }
            // Perbarui data di database
            KJPP::where('id', $id)->update($validated);

            return redirect()
                ->route('basicdata.kjpp.index')
                ->with('success', 'KJPP updated successfully');
        } else {
            return redirect()
                ->route('basicdata.kjpp.edit', $id)
                ->with('error', 'Validation failed');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $kjpp = KJPP::find($id);

            // Jangan hapus file default.pdf
            if ($kjpp->attachment && $kjpp->attachment !== 'default.pdf') {
                Storage::delete('public/uploads_pdf/' . $kjpp->attachment);
            }

            // Hapus data dari database
            $kjpp->delete();

            echo json_encode(['success' => true, 'message' => 'KJPP deleted successfully']);
        } catch (Throwable $e) {
            echo json_encode(['success' => false, 'message' => 'Failed to delete branch: ' . $e]);
        }
    }

    public function dataForDatatables(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('kjpp.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        // Retrieve data from the database order by code ascending
        $query = KJPP::query()->orderBy('code', 'asc');

        // 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('code', 'LIKE', "%$search%");
                $q->orWhere('name', 'LIKE', "%$search%");
                $q->orWhere('jenis_kantor', 'LIKE', "%$search%");
            });
        }

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

        // 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->with('city')->get();

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

        // Calculate the current page number
        $currentPage = 0 + 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'            => $data,
        ]);
    }

    public function export()
    {
        return Excel::download(new KJPPExport, 'kjpp.xlsx');
    }
}
