<?php

namespace App\Http\Controllers;

use App\Models\Organization;
use App\Services\OrganogramService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

/**
 * OrganogramController
 *
 * Handles displaying and exporting organizational hierarchy charts.
 * Only accessible by users with Super Manager or Manager roles.
 */
class OrganogramController extends Controller
{
    /**
     * The organogram service instance.
     */
    protected OrganogramService $organogramService;

    /**
     * Create a new controller instance.
     */
    public function __construct(OrganogramService $organogramService)
    {
        $this->organogramService = $organogramService;
    }

    /**
     * Display the organogram visualization.
     */
    public function show(Request $request): View
    {
        abort_unless(auth()->user()->can('view organogram'), 403,
            'You do not have permission to view the organogram.');

        $organizations = Organization::orderBy('name')->get();
        $selectedOrganization = null;
        $hierarchy = [];
        $statistics = [];

        if ($request->filled('organization_id')) {
            $selectedOrganization = Organization::find($request->organization_id);

            if ($selectedOrganization) {
                $hierarchy = $this->organogramService->buildHierarchy($selectedOrganization);
                $statistics = $this->organogramService->getStatistics($selectedOrganization);
            }
        } elseif ($organizations->count() === 1) {
            // Auto-select if only one organization exists
            $selectedOrganization = $organizations->first();
            $hierarchy = $this->organogramService->buildHierarchy($selectedOrganization);
            $statistics = $this->organogramService->getStatistics($selectedOrganization);
        }

        return view('organization.organogram.show', compact(
            'organizations',
            'selectedOrganization',
            'hierarchy',
            'statistics'
        ));
    }

    /**
     * Export the organogram in the specified format.
     */
    public function export(Request $request, string $format)
    {
        abort_unless(auth()->user()->can('export organogram'), 403,
            'You do not have permission to export the organogram.');

        $validated = $request->validate([
            'organization_id' => 'required|exists:organizations,id',
        ], [
            'organization_id.required' => 'Please select an organization to export.',
        ]);

        $organization = Organization::findOrFail($validated['organization_id']);

        $allowedFormats = ['pdf', 'png', 'svg', 'json'];
        if (!in_array($format, $allowedFormats)) {
            return redirect()
                ->route('organization.organogram.show')
                ->with('error', "Unsupported export format: {$format}");
        }

        try {
            $result = $this->organogramService->export($organization, $format);

            if ($format === 'json') {
                return response()->json($result)
                    ->header('Content-Disposition', 'attachment; filename="organogram_' . $organization->id . '.json"');
            }

            if ($format === 'svg') {
                return response($result)
                    ->header('Content-Type', 'image/svg+xml')
                    ->header('Content-Disposition', 'attachment; filename="organogram_' . $organization->id . '.svg"');
            }

            // For PDF and PNG, return the file path for download
            return response()->download($result);

        } catch (\InvalidArgumentException $e) {
            return redirect()
                ->route('organization.organogram.show')
                ->with('error', $e->getMessage());
        } catch (\Exception $e) {
            return redirect()
                ->route('organization.organogram.show')
                ->with('error', 'Failed to export organogram. Please try again.');
        }
    }

    /**
     * Get hierarchy data as JSON for AJAX requests.
     */
    public function getHierarchy(Organization $organization)
    {
        abort_unless(auth()->user()->can('view organogram'), 403);

        $hierarchy = $this->organogramService->buildHierarchy($organization);
        $statistics = $this->organogramService->getStatistics($organization);

        return response()->json([
            'organization' => [
                'id' => $organization->id,
                'name' => $organization->name,
            ],
            'hierarchy' => $hierarchy,
            'statistics' => $statistics,
        ]);
    }

    /**
     * Get flat list of positions for AJAX requests.
     */
    public function getFlatList(Organization $organization)
    {
        abort_unless(auth()->user()->can('view organogram'), 403);

        $flatList = $this->organogramService->buildFlatList($organization);

        return response()->json($flatList);
    }
}
