<?php

namespace App\Http\Controllers;

use App\Models\TaxType;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Carbon\Carbon;

class TaxTypeController extends Controller
{
    public function index()
    {
        $data = TaxType::with('taxName')->get();

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

    public function show(Request $request)
    {
        $data = TaxType::with('taxName')->find($request->id);

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

    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|unique:tax_types,code',
            'tax_name_id' => 'required|exists:tax_names,id',
            'category' => 'nullable|string',
            'rate' => 'nullable|numeric',
            'tax_base_type' => ['required', Rule::in(['price', 'formula'])],
            'tax_base_formula' => 'nullable|string',
            'status' => 'nullable|boolean',
            'description' => 'nullable|string',
            'legal_basis' => 'nullable|string',
            'updated_date' => 'nullable|date',
        ]);

        $data = new TaxType;
        $data->code = $request->code;
        $data->tax_name_id = $request->tax_name_id;
        $data->category = $request->category;
        $data->rate = $request->rate;
        $data->tax_base_type = $request->tax_base_type;
        $data->tax_base_formula = $request->tax_base_formula;
        $data->status = $request->status;
        $data->description = $request->description;
        $data->legal_basis = $request->legal_basis;
        $data->updated_date = $request->updated_date ?? Carbon::now()->toDateString();
        $data->save();

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

    public function update(Request $request)
    {
        $request->validate([
            'code' => [
                'required',
                'string',
                Rule::unique('tax_types', 'code')->ignore($request->id),
            ],
            'tax_name_id' => 'required|exists:tax_names,id',
            'category' => 'nullable|string',
            'rate' => 'nullable|numeric',
            'tax_base_type' => ['required', Rule::in(['price', 'formula'])],
            'tax_base_formula' => 'nullable|string',
            'status' => 'nullable|boolean',
            'description' => 'nullable|string',
            'legal_basis' => 'nullable|string',
            'updated_date' => 'nullable|date',
        ]);

        $data = TaxType::findOrFail($request->id);
        $data->code = $request->code;
        $data->tax_name_id = $request->tax_name_id;
        $data->category = $request->category;
        $data->rate = $request->rate;
        $data->tax_base_type = $request->tax_base_type;
        $data->tax_base_formula = $request->tax_base_formula;
        $data->status = $request->status;
        $data->description = $request->description;
        $data->legal_basis = $request->legal_basis;
        $data->updated_date = $request->updated_date ?? Carbon::now()->toDateString();
        $data->save();

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

    public function destroy(Request $request)
    {
        $data = TaxType::findOrFail($request->id);
        $data->delete();

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

    public function testCalculation(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:tax_types,id',
            'amount' => 'required|numeric',
        ]);

        $taxType = TaxType::findOrFail($request->id);

        if ($taxType->tax_base_type !== 'formula') {
            return response([
                'success' => false,
                'message' => 'Tax type is not formula based',
            ], 400);
        }

        if (empty($taxType->tax_base_formula)) {
            return response([
                'success' => false,
                'message' => 'Formula is empty',
            ], 400);
        }

        try {
            // Gunakan library math parser atau eval dengan sangat hati-hati
            // Di sini kita gunakan eval sederhana namun dengan sanitasi ketat
            // Hanya izinkan angka, titik, operator +, -, *, /, (, )
            $formula = $taxType->tax_base_formula;

            // Validasi karakter formula agar aman
            if (!preg_match('/^[\d\.\+\-\*\/\(\)\s]+$/', $formula)) {
                return response([
                    'success' => false,
                    'message' => 'Formula contains invalid characters',
                ], 400);
            }

            // Hitung nilai formula terlebih dahulu
            // Misalnya formula "11/12", kita hitung hasilnya
            $formulaResult = 0;
            eval('$formulaResult = ' . $formula . ';');

            // Hitung hasil akhir: formulaResult * amount
            $result = $formulaResult * $request->amount;

            return response([
                'success' => true,
                'data' => [
                    'tax_type' => $taxType->code,
                    'formula' => $formula,
                    'amount' => $request->amount,
                    'formula_result' => $formulaResult,
                    'calculation_result' => $result
                ],
            ], 200);
        } catch (\Throwable $th) {
            return response([
                'success' => false,
                'message' => 'Error calculating formula: ' . $th->getMessage(),
            ], 500);
        }
    }
}
