<?php

namespace App\Http\Controllers;

use App\Models\TaxFiscalCorrection;
use App\Models\Licence;
use App\Http\Controllers\AkunController;
use Illuminate\Http\Request;

class TaxFiscalCorrectionController extends Controller
{
    /**
     * Get tax fiscal corrections by corporate income ID.
     *
     * @param  int  $corporateIncomeId
     * @return \Illuminate\Http\Response
     */
    public function getByCorporateIncomeId($corporateIncomeId)
    {
        $items = TaxFiscalCorrection::where('corporateincome_id', $corporateIncomeId)
            ->get();

        $licence = Licence::first();
        $companyType = $licence ? $licence->company_type : null;

        $lang = AkunController::getActiveLanguage();
        $langCode = $lang->code ?? 'id';

        $mappingData = $this->loadAkunMapping($langCode);

        foreach ($items as $item) {
            if (!empty($item->akun_desc)) {
                $item->akun_desc = $this->translateAccountName($item->akun_desc, $companyType, $mappingData);
            }
        }

        return response([
            'success' => true,
            'data' => $items
        ], 200);
    }

    private function loadAkunMapping($langCode = 'id')
    {
        $jsonPath = config_path("lang/{$langCode}/akun.json");

        if (!file_exists($jsonPath)) {
            $jsonPath = config_path('lang/id/akun.json');
        }

        if (!file_exists($jsonPath)) {
            return [];
        }

        return json_decode(file_get_contents($jsonPath), true) ?? [];
    }

    private function translateAccountName($accountName, $companyType, $mappingData)
    {
        if ($companyType && isset($mappingData[$companyType][$accountName])) {
            return $mappingData[$companyType][$accountName];
        }

        if (isset($mappingData['akun_umum'][$accountName])) {
            return $mappingData['akun_umum'][$accountName];
        }

        return $accountName;
    }
}
