<?php

namespace App\Http\Controllers;

use App\Audit;
use App\Polis;
use App\Cawangan;
use App\LookupAlasan;
use App\Palsu;
use App\Gadai;
use App\Pampasan;
use Illuminate\Http\Request;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class BarangkesController extends Controller
{
    public function LaporanBarangKes(Request $request)
    {
        $status = $request->status;

        $cawangan = Cawangan::on('mysql7')->where('kodcaw', $request->kodcaw)->first();

        if (!$cawangan) {
            return response()->json(['error' => 'Invalid kodcaw'], 403);
        }

        $palsu_query = Palsu::on($cawangan['mysql'])
            ->select([
                'tarikh',
                'norujukan',
                'nota',
                'pembiayaan',
                'nilaimarhun',
                'jbg',
                'untung',
                'untungonepercent',
                'untungcajlain'
            ])
            ->when($request->filled('tarikh_mula') && $request->filled('tarikh_akhir'), function ($query) use ($request) {
                return $query->whereBetween('tarikh', [$request->tarikh_mula, $request->tarikh_akhir]);
            })
            ->with(['tebus:norujukan', 'gadai:norujukan,nokp']);

        $palsu_array = $palsu_query->get()->toArray();
        $pampasan_array = Pampasan::on($cawangan['mysql'])->where('kodcaw', $request->kodcaw)->get()->toArray();

        $indexedArray2 = collect($pampasan_array)->keyBy('norujukan');

        $merged = collect($palsu_array)->map(function ($item) use ($indexedArray2) {
            $id = $item['norujukan'];
            $itemArray = $item; // Already an array from toArray()
            $additional = $indexedArray2->get($id, []);

            // Add exists_in_tebus flag based on relationship
            $itemArray['gadaian_sudah_tebus'] = !is_null($item['tebus']);

            // Add nokp customer from gadai relationship
            $itemArray['nokp'] = $item['gadai']['nokp'];

            // Remove the tebus relationship data to keep response clean
            unset($itemArray['tebus']);
            unset($itemArray['gadai']);


            return array_merge($itemArray, $additional);
        })->values()->toArray();

        $filteredResults = [];

        $sudahTuntutSecaraManual = [
            '011237240719-0015',
            '011237240806-0011',
            '011237240828-0001',
            '011237240731-0026',
            '011237240912-0009'
        ];

        // if ($status == 'dituntut') {
        //     foreach ($merged as $pampasan) {
        //         if (isset($pampasan['status']) && $pampasan['status'] == 1) {
        //             $filteredResults[] = $pampasan;
        //         }
        //     }
        // }
        if ($status == 'dituntut') {
            foreach ($merged as $pampasan) {
                if (
                    (isset($pampasan['status']) && $pampasan['status'] == 1)
                    || in_array($pampasan['norujukan'], $sudahTuntutSecaraManual)
                ) {
                    $filteredResults[] = $pampasan;
                }
            }
        }
        // if ($status == 'belum-tuntut') {
        //     foreach ($merged as $pampasan) {
        //         if (!isset($pampasan['status'])) {
        //             $filteredResults[] = $pampasan;
        //         }
        //     }
        // }
        if ($status == 'belum-tuntut') {
            foreach ($merged as $pampasan) {
                if (
                    !isset($pampasan['status'])
                    && !in_array($pampasan['norujukan'], $sudahTuntutSecaraManual)
                ) {
                    $filteredResults[] = $pampasan;
                }
            }
        }
        if ($status == 'all' || $status == null) {
            $filteredResults = $merged;
        }

        return response()->json($filteredResults);
    }

    public function store(Request $request) //cara fifi ajar
    {

        $current = Carbon::now();
        $kodcaw = $request->kodcaw;
        $cawangan = Cawangan::on('mysql7')
            ->where('kodcaw', $kodcaw)
            ->first();

        $insert = Palsu::on($cawangan['mysql'])->create([
            'kodcaw'            => $request->kodcaw,
            'tarikh'            => $current->toDateString(),
            'norujukan'         => $request->norujukan,
            'teller'            => $request->teller,
            'nota'              => $request->nota ? $request->nota : '',
            'pembiayaan'        => $request->pinjaman,
            'nilaimarhun'       => $request->nilaimarhun,
            'jbg'               => $request->jbg,
            'untung'            => $request->tunggakan,
            'untungonepercent'  => $request->tunggakanonepercent,
            'untungcajlain'     => $request->tunggakanujrah,
        ]);

        // return $insert;

        return response()->json([
            'success' => true,
            'message' => 'Barang kes berjaya didaftar',
            'data'    => $insert
        ], 201);
    }

    public function update(Request $request)
    {

        $current = Carbon::now();
        $kodcaw = $request->kodcaw;
        Log::info($request->all());

        // Cari connection cawangan
        $cawangan = Cawangan::on('mysql7')
            ->where('kodcaw', $kodcaw)
            ->first();

        if (!$cawangan) {
            return response()->json([
                'success' => false,
                'message' => 'Cawangan tidak dijumpai',
            ], 404);
        }

        // Update direct (ikut norujukan)
        $palsu = palsu::on($cawangan['mysql'])
            ->where('norujukan', $request->norujukan)
            ->update([
                'kodcaw'            => $request->kodcaw,
                'tarikh'            => $request->tarikh,
                'teller'            => $request->teller,
                'nota'              => $request->nota ?? '',
                'pembiayaan'          => $request->pinjaman,
                'nilaimarhun'       => $request->nilaimarhun,
                'jbg'               => $request->jbg,
                'untung'            => $request->tunggakan,
                'untungonepercent'  => $request->tunggakanonepercent,
                'untungcajlain'     => $request->tunggakanujrah,
            ]);

        return response()->json([
            'success' => $palsu ? true : false,
            'message' => $palsu ? 'Rekod gadai berjaya dikemaskini' : 'Rekod tidak dijumpai',
        ], 200);
    }
}
