<?php

namespace App\Http\Controllers;

use App\Models\Akun;
use App\Models\CorporateIncomeTax;
use App\Models\CreditCashTransaction;
use App\Models\TaxFiscalCorrection;
use App\Models\Language;
use App\Models\Licence;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CorporateIncomeTaxController extends Controller
{
    public function index(Request $request)
    {
        $query = CorporateIncomeTax::with(['creditCashTransactions.isfrom', 'creditCashTransactions.isto', 'taxFiscalCorrections'])
            ->orderBy('date', 'desc');

        if ($request->filled('type')) {
            $query->where('transaction_category', $request->type);
        }

        $items = $query->get();

        // Handle locale translation for isfrom and isto
        $activeLang = Language::where('status', true)->first();
        $langCode = $activeLang ? $activeLang->code : 'id';
        $mappingData = $this->loadAkunMapping($langCode);

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

        foreach ($items as $item) {
            foreach ($item->creditCashTransactions as $transaction) {
                if ($transaction->isfrom) {
                    $transaction->isfrom->name = $this->translateAccountName($transaction->isfrom->name, $companyType, $mappingData);
                }
                if ($transaction->isto) {
                    $transaction->isto->name = $this->translateAccountName($transaction->isto->name, $companyType, $mappingData);
                }
            }
        }

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

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

        // Fallback to Indonesian if file not found
        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)
    {
        // Prioritize translation based on company type
        if ($companyType && isset($mappingData[$companyType][$accountName])) {
            return $mappingData[$companyType][$accountName];
        }

        // Fallback to general translation
        if (isset($mappingData['akun_umum'][$accountName])) {
            return $mappingData['akun_umum'][$accountName];
        }

        // If not found, return original name
        return $accountName;
    }

    public function show($id)
    {
        $item = CorporateIncomeTax::find($id);

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

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

    public function store(Request $request)
    {
        $request->validate([
            'tax_base' => 'required|numeric',
            'rate' => 'required|numeric',
            'tax_amount' => 'required|numeric',
            'transaction_category' => 'required|string',
            'pph28_amount' => 'nullable|numeric',
            'date' => 'required|date',
            'staff' => 'required|string',
            'receivables' => 'array',
            'receivables.*.akun_id' => 'required_with:receivables|integer',
            'receivables.*.total' => 'required_with:receivables|numeric',
            'income_details' => 'nullable|array',
            'income_details.*.akun_desc' => 'required_with:income_details|string',
            'income_details.*.commercial_amount' => 'nullable|numeric',
            'income_details.*.positive_correction' => 'nullable|numeric',
            'income_details.*.negative_correction' => 'nullable|numeric',
            'income_details.*.fiscal_amount' => 'nullable|numeric',
        ]);

        DB::beginTransaction();

        try {
            $item = new CorporateIncomeTax();
            $item->tax_base = $request->tax_base;
            $item->rate = $request->rate;
            $item->tax_amount = $request->tax_amount;
            $item->transaction_category = $request->transaction_category;
            $item->date = date("Y-m-d", strtotime($request->date));
            $item->staff = $request->staff;
            $item->save();

            if ($item->transaction_category === 'normal') {
                $receivables = $request->input('receivables', []);

                foreach ($receivables as $piutang) {
                    if (!isset($piutang['akun_id'], $piutang['total'])) {
                        continue;
                    }

                    $creditCash = new CreditCashTransaction();
                    $creditCash->corporateincome_id = $item->id;
                    $creditCash->from_id = $piutang['akun_id'];
                    $creditCash->total = $piutang['total'];
                    $creditCash->staff = $request->staff;
                    $creditCash->date = date("Y-m-d", strtotime($request->date));
                    $creditCash->save();
                }

                if ($request->pph28_amount > 0) {
                    $akunpiutangpph28 = Akun::where('name', 'Piutang_PPh_28')->first();
                    $creditCash28 = new CreditCashTransaction();
                    $creditCash28->corporateincome_id = $item->id;
                    $creditCash28->to_id = $akunpiutangpph28->id;
                    $creditCash28->total = $request->pph28_amount;
                    $creditCash28->staff = $request->staff;
                    $creditCash28->date = date("Y-m-d", strtotime($request->date));
                    $creditCash28->save();
                }

                $incomeDetails = $request->input('income_details', []);
                foreach ($incomeDetails as $detail) {
                    if (!isset($detail['akun_desc'])) {
                        continue;
                    }

                    $fiscalCorrection = new TaxFiscalCorrection();
                    $fiscalCorrection->corporateincome_id = $item->id;
                    $fiscalCorrection->akun_desc = $detail['akun_desc'];
                    $fiscalCorrection->commercial_amount = $detail['commercial_amount'] ?? 0;
                    $fiscalCorrection->positive_correction = $detail['positive_correction'] ?? 0;
                    $fiscalCorrection->negative_correction = $detail['negative_correction'] ?? 0;
                    $fiscalCorrection->fiscal_amount = $detail['fiscal_amount'] ?? 0;
                    $fiscalCorrection->save();
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response([
                'success' => false,
                'message' => 'Failed to create corporate income tax',
            ], 500);
        }

        return response([
            'success' => true,
            'message' => 'Corporate income tax created successfully',
            'data' => $item
        ], 201);
    }

    public function storeReceivables(Request $request)
    {
        $request->validate([
            'tax_base' => 'required|numeric',
            'transaction_category' => 'required|string',
            'date' => 'required|date',
            'staff' => 'required|string',
            'receivables' => 'required|array',
            'receivables.*.akun_id' => 'required|integer',
            'receivables.*.total' => 'required|numeric',
        ]);

        DB::beginTransaction();

        try {
            $item = new CorporateIncomeTax();
            $item->tax_base = $request->tax_base;
            $item->rate = 0;
            $item->tax_amount = 0;
            $item->transaction_category = $request->transaction_category;
            $item->date = date("Y-m-d", strtotime($request->date));
            $item->staff = $request->staff;
            $item->save();

            $receivables = $request->input('receivables', []);
            foreach ($receivables as $piutang) {
                if (!isset($piutang['akun_id'], $piutang['total'])) {
                    continue;
                }

                $creditCash = new CreditCashTransaction();
                $creditCash->corporateincome_id = $item->id;
                $creditCash->from_id = $piutang['akun_id'];
                $creditCash->total = $piutang['total'];
                $creditCash->staff = $request->staff;
                $creditCash->date = date("Y-m-d", strtotime($request->date));
                $creditCash->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response([
                'success' => false,
                'message' => 'Failed to create corporate income tax',
            ], 500);
        }

        return response([
            'success' => true,
            'message' => 'Corporate income tax created successfully',
            'data' => $item
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $item = CorporateIncomeTax::find($id);

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

        $request->validate([
            'tax_base' => 'required|numeric',
            'rate' => 'required|numeric',
            'tax_amount' => 'required|numeric',
            'transaction_category' => 'required|string',
            'date' => 'required|date',
            'staff' => 'required|string',
        ]);

        $item->tax_base = $request->tax_base;
        $item->rate = $request->rate;
        $item->tax_amount = $request->tax_amount;
        $item->transaction_category = $request->transaction_category;
        $item->date = date("Y-m-d", strtotime($request->date));
        $item->staff = $request->staff;
        $item->save();

        return response([
            'success' => true,
            'message' => 'Corporate income tax updated successfully',
            'data' => $item
        ], 200);
    }

    public function destroy($id)
    {
        $item = CorporateIncomeTax::find($id);

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

        DB::beginTransaction();
        try {
            if ($item->transaction_category === 'normal') {
                CreditCashTransaction::where('corporateincome_id', $item->id)->delete();
                TaxFiscalCorrection::where('corporateincome_id', $item->id)->delete();
            }

            $item->delete();
            DB::commit();

            return response([
                'success' => true,
                'message' => 'Corporate income tax deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            DB::rollBack();
            return response([
                'success' => false,
                'message' => 'Failed to delete corporate income tax'
            ], 500);
        }
    }
}
