<?php

namespace App\Http\Controllers;

use App\Models\LeadershipHistory;
use App\Models\LeadershipAchievement;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * LeadershipHistoryController
 *
 * Handles viewing leadership history records and adding achievements.
 * History records are read-only from user perspective.
 * Only accessible by users with Super Manager or Manager roles.
 */
class LeadershipHistoryController extends Controller
{
    /**
     * Display a listing of leadership history records.
     */
    public function index(Request $request): View
    {
        abort_unless(auth()->user()->can('view leadership history'), 403,
            'You do not have permission to view leadership history.');

        $query = LeadershipHistory::with(['organization', 'leadershipPosition', 'user', 'achievements'])
            ->withCount('achievements');

        // Filter by position
        if ($request->filled('position_id')) {
            $query->where('leadership_position_id', $request->position_id);
        }

        // Filter by user
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // Filter by organization
        if ($request->filled('organization_id')) {
            $query->where('organization_id', $request->organization_id);
        }

        // Filter by date range
        if ($request->filled('start_date') && $request->filled('end_date')) {
            $query->dateRange($request->start_date, $request->end_date);
        }

        // Search by name or position title
        if ($request->filled('search')) {
            $query->search($request->search);
        }

        $histories = $query->orderByTermStart()->paginate(20);

        // Get filter options
        $organizations = \App\Models\Organization::orderBy('name')->get();
        $positions = \App\Models\LeadershipPosition::orderBy('title')->get();

        return view('organization.leadership-history.index', compact('histories', 'organizations', 'positions'));
    }

    /**
     * Display the specified leadership history record.
     */
    public function show(LeadershipHistory $leadershipHistory): View
    {
        abort_unless(auth()->user()->can('view leadership history'), 403,
            'You do not have permission to view leadership history.');

        $leadershipHistory->load(['organization', 'leadershipPosition', 'user', 'achievements' => function ($query) {
            $query->orderByDate();
        }]);

        return view('organization.leadership-history.show', compact('leadershipHistory'));
    }

    /**
     * Add an achievement to a leadership history record.
     */
    public function addAchievement(Request $request, LeadershipHistory $leadershipHistory): RedirectResponse
    {
        abort_unless(auth()->user()->can('add leadership achievements'), 403,
            'You do not have permission to add leadership achievements.');

        $validated = $request->validate([
            'achievement_description' => 'required|string',
            'achievement_date' => 'required|date|before_or_equal:today',
        ], [
            'achievement_description.required' => 'Achievement description is required.',
            'achievement_date.required' => 'Achievement date is required.',
            'achievement_date.before_or_equal' => 'Achievement date cannot be in the future.',
        ]);

        // XSS Prevention
        $validated['achievement_description'] = strip_tags($validated['achievement_description']);

        $leadershipHistory->addAchievement(
            $validated['achievement_description'],
            $validated['achievement_date']
        );

        return redirect()
            ->route('organization.leadership-history.show', $leadershipHistory)
            ->with('success', 'Achievement added successfully!');
    }

    /**
     * Delete an achievement from a leadership history record.
     */
    public function deleteAchievement(LeadershipAchievement $achievement): RedirectResponse
    {
        abort_unless(auth()->user()->can('add leadership achievements'), 403,
            'You do not have permission to manage leadership achievements.');

        $historyId = $achievement->leadership_history_id;
        $achievement->delete();

        return redirect()
            ->route('organization.leadership-history.show', $historyId)
            ->with('success', 'Achievement deleted successfully!');
    }
}
