<?php

namespace App\Http\Controllers;

use App\Models\ProductionCostSetting;
use App\Models\Akun;
use App\Models\Language;
use App\Models\Licence;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ProductionCostSettingController extends Controller
{
    private function getActiveLanguage()
    {
        return Language::where('status', true)->first();
    }

    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 (isset($mappingData[$companyType][$accountName])) {
            return $mappingData[$companyType][$accountName];
        }
        if (isset($mappingData['akun_umum'][$accountName])) {
            return $mappingData['akun_umum'][$accountName];
        }
        return $accountName;
    }

    public function index()
    {
        $data = ProductionCostSetting::with('akun')->orderBy('id', 'desc')->get();

        $lang = $this->getActiveLanguage();
        $langCode = $lang->code ?? 'id';
        $mappingData = $this->loadAkunMapping($langCode);
        $licence = Licence::first();
        $companyType = $licence ? $licence->company_type : 'general';

        foreach ($data as $item) {
            if ($item->akun) {
                $item->akun->rename = $this->translateAccountName($item->akun->name, $companyType, $mappingData);
            }
        }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'akun_id' => ['nullable', 'integer', 'exists:akuns,id'],
            'cost_estimate' => ['required', 'numeric', 'min:0'],
        ]);

        $setting = new ProductionCostSetting;
        $akun = null;
        if (!empty($validated['akun_id'])) {
            $akun = Akun::find($validated['akun_id']);
        }
        $category = 'overhead_cost';
        if ($akun) {
            if ($akun->name === 'biaya_tenaga_kerja_langsung_dibebankan') {
                $category = 'direct_labor_cost';
            } elseif (!!$akun->is_productionasset) {
                $category = 'depreciation_cost';
            }
        }
        $setting->category = $category;
        $setting->akun_id = $validated['akun_id'] ?? null;
        $setting->cost_estimate = $validated['cost_estimate'];
        $setting->save();

        return response([
            'success' => true,
            'data' => $setting->load('akun'),
        ], 201);
    }

    public function show($id)
    {
        $setting = ProductionCostSetting::with('akun')->find($id);

        if (!$setting) {
            return response([
                'success' => false,
                'message' => 'not found',
            ], 404);
        }

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

    public function showByAkun($akunId)
    {
        $setting = ProductionCostSetting::with('akun')->where('akun_id', $akunId)->first();

        if (!$setting) {
            return response([
                'success' => false,
                'message' => 'not found',
            ], 204);
        }

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

    public function update(Request $request, $id)
    {
        $setting = ProductionCostSetting::find($id);

        if (!$setting) {
            return response([
                'success' => false,
                'message' => 'not found',
            ], 404);
        }

        $validated = $request->validate([
            'akun_id' => ['nullable', 'integer', 'exists:akuns,id'],
            'cost_estimate' => ['required', 'numeric', 'min:0'],
        ]);

        $akun = null;
        if (!empty($validated['akun_id'])) {
            $akun = Akun::find($validated['akun_id']);
        }
        $category = 'overhead_cost';
        if ($akun) {
            if ($akun->name === 'biaya_tenaga_kerja_langsung_dibebankan') {
                $category = 'direct_labor_cost';
            } elseif (!!$akun->is_productionasset) {
                $category = 'depreciation_cost';
            }
        }
        $setting->category = $category;
        $setting->akun_id = $validated['akun_id'] ?? null;
        $setting->cost_estimate = $validated['cost_estimate'];
        $setting->save();

        return response([
            'success' => true,
            'data' => $setting->load('akun'),
        ], 200);
    }

    public function destroy($id)
    {
        $setting = ProductionCostSetting::find($id);

        if (!$setting) {
            return response([
                'success' => false,
                'message' => 'not found',
            ], 404);
        }

        $setting->delete();

        return response([
            'success' => true,
            'message' => 'deleted',
        ], 200);
    }
}
