<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\ChartOfAccountService;
use Illuminate\Http\JsonResponse;

class ChartOfAccountController extends Controller
{
    protected $chartOfAccountService;

    public function __construct(ChartOfAccountService $chartOfAccountService)
    {
        $this->chartOfAccountService = $chartOfAccountService;
    }

    /**
     * Get the top 5 parent chart of accounts with their complete hierarchy
     * including children and linked accounts
     *
     * @return JsonResponse
     */
    public function getHierarchyWithAccounts(): JsonResponse
    {
        try {
            $hierarchy = $this->chartOfAccountService->getHierarchyWithAccounts();

            return response()->json([
                'success' => true,
                'data' => $hierarchy,
                'message' => 'Chart of accounts hierarchy retrieved successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving chart of accounts hierarchy: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get a specific chart of account with its complete hierarchy
     *
     * @param int $id
     * @return JsonResponse
     */
    public function getChartOfAccountHierarchy(int $id): JsonResponse
    {
        try {
            $hierarchy = $this->chartOfAccountService->getChartOfAccountHierarchy($id);

            if (!$hierarchy) {
                return response()->json([
                    'success' => false,
                    'message' => 'Chart of account not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $hierarchy,
                'message' => 'Chart of account hierarchy retrieved successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving chart of account hierarchy: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all chart of accounts in a flat structure with their accounts
     *
     * @return JsonResponse
     */
    public function getAllWithAccounts(): JsonResponse
    {
        try {
            $chartOfAccounts = $this->chartOfAccountService->getAllWithAccounts();

            return response()->json([
                'success' => true,
                'data' => $chartOfAccounts,
                'message' => 'Chart of accounts retrieved successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error retrieving chart of accounts: ' . $e->getMessage()
            ], 500);
        }
    }
}
