<?php

namespace App\Http\Controllers;

use App\Cawangan;
use App\PayableUjrahBranch;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class PayableUjrahBranchController extends Controller
{

    public function index()
    {
        $this->syncCawangan();

        return PayableUjrahBranch::with('cawangan_information')->get()->toJson();
    }

    public function syncCawangan()
    {
        $arrahn_master_db_cawangan = Cawangan::select(['kodcaw', 'details_caw']);
        $payableUjrahBranch = PayableUjrahBranch::all()->pluck('kodcaw');
        $diff_cawangan = $arrahn_master_db_cawangan->get()->pluck('kodcaw')->diff($payableUjrahBranch);

        if($diff_cawangan->count() > 0) {
           $diff_cawangan->each(function($new_cawangan) use($arrahn_master_db_cawangan){
                $cawangan = $arrahn_master_db_cawangan->where('kodcaw', $new_cawangan)->first();
                PayableUjrahBranch::create([
                    'kodcaw' => $cawangan->kodcaw,
                    'details_caw' => $cawangan->details_caw,
                    'gadaian_ujrah_payable' => 0,
                ]);
           });
        }
    }

    public function create(Request $request)
    {
        $validated_data = $request->validate([
            'details_caw' => 'required',
            'kodcaw' => 'required',
        ]);

        $created_branch = PayableUjrahBranch::create($validated_data);

        return response(json_encode($created_branch), 200);
    }

    public function syncStatus(Request $request)
    {

        $getDetailCawanganFromKodCaw = function($kodcaw){
            $cawangan_details = Cawangan::all(['kodcaw', 'details_caw']);
            return $cawangan_details->where('kodcaw', $kodcaw)->first()->details_caw;
        };

        // payable ujrah updates
        $previous_payable_ujrah_branch = PayableUjrahBranch::select('kodcaw as branch', 'gadaian_ujrah_payable')->get();

        $payable_ujrah_branch = collect($request->gadai_ujrah_payable_branches);

        $payable_ujrah_branch_updates = $this->findDiff($previous_payable_ujrah_branch, $payable_ujrah_branch, 'branch');

        $payable_ujrah_branch_updates->each(function ($item, $key) {
            PayableUjrahBranch::where('kodcaw', $key)->update(['gadaian_ujrah_payable' => $item['gadaian_ujrah_payable']]);
        });

        $generateUpdateMessagePayableUjrahBranch = function($updateData) use($getDetailCawanganFromKodCaw){

            return $updateData->map(function($item, $index) use($getDetailCawanganFromKodCaw) {
                $cawanganName = $getDetailCawanganFromKodCaw($index);

                $gadaian_ujrah_payable_note =  $item['gadaian_ujrah_payable'] === 0 ? 'gadaian ujrah payment disabled' : 'gadaian ujrah payment  enabled';

                return "$cawanganName $gadaian_ujrah_payable_note";
            });

        };


        // tawarruq version updates
        $previous_branch_tawarruq_version = Cawangan::select('kodcaw as branch', 'version as tawarruq_version')->get();

        $branch_tawarruq_version = collect($request->branch_tawarruq_version);

        $arrahn_master_db_updates = $this->findDiff($previous_branch_tawarruq_version, $branch_tawarruq_version, 'branch');

        $arrahn_master_db_updates->each(function ($item, $key) {
            Cawangan::where('kodcaw', $key)->update(['version' => $item['tawarruq_version']]);
        });

        $generateUpdateMessageTawarruqVersion = function($updateData) use($getDetailCawanganFromKodCaw){

            return $updateData->map(function($item, $index) use($getDetailCawanganFromKodCaw) {
                $cawanganName = $getDetailCawanganFromKodCaw($index);

                $tawarruq_version =  $item['tawarruq_version'];
                return "$cawanganName change to use tawarruq version : $tawarruq_version";
            });

        };

        return response()->json([
            'status' => 'success',
            'updates_done' => [
                'updated_branch_tawarruq_version' => $generateUpdateMessageTawarruqVersion($arrahn_master_db_updates),
                'updated_payable_ujrah' => $generateUpdateMessagePayableUjrahBranch($payable_ujrah_branch_updates),
            ]
        ]);
    }



    public function delete()
    {
    }

    // SUPPORTING METHODS
    public function findDiff(Collection $collectionA, Collection $collectionB, $compare_key = 'id')
    {
        // Filter and find differences
        $differences = $collectionA->mapWithKeys(function ($itemA) use ($collectionB, $compare_key) {
            $itemB = $collectionB->firstWhere($compare_key, $itemA[$compare_key]);

            if ($itemB) {
                $diff = collect($itemB)->diffAssoc($itemA);
                if ($diff->isNotEmpty()) {
                    return [$itemA[$compare_key] => $diff];
                }
            } else {
                return [$itemA[$compare_key] => collect($itemA)];
            }

            return [];
        })->filter();

        return $differences;
    }
}
