<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\OrganizationalUnit;
use App\Models\Question;
use App\Models\UnitType;
use Alert;
use Illuminate\Support\Facades\Auth;

class OrganizationalUnitController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $organizationalUnits = OrganizationalUnit::with(['parent', 'unitType', 'children', 'creator'])
            ->withCount('officeAnswers')
            ->get();
        return view('organizational-units.index', compact('organizationalUnits'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $unitTypes = UnitType::all();
        $parentUnits = OrganizationalUnit::with('unitType')->get();
        return view('organizational-units.create', compact('unitTypes', 'parentUnits'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:organizational_units,id',
            'unit_type_id' => 'required|exists:unit_types,id',
        ];

        $validatedData = $request->validate($rules);
        $validatedData['created_by'] = Auth::id();

        OrganizationalUnit::create($validatedData);

        Alert::success('نجاح', 'تمت إضافة الوحدة التنظيمية بنجاح!');
        return redirect()->route('organizational-units.index');
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, OrganizationalUnit $organizationalUnit)
    {
        // Load all descendants recursively with their children
        $organizationalUnit->load(['parent', 'unitType', 'creator']);
        
        // Load children recursively
        $organizationalUnit->load(['children.unitType', 'children.children.unitType', 'children.children.children.unitType']);

        // Load office answers and questions to compute safety
        $organizationalUnit->load(['officeAnswers.question']);
        
        $answers = $organizationalUnit->officeAnswers;
        $safeAnswersCount = 0;
        $unsafeAnswersCount = 0;
        $hasQuestionsWithSafeAnswers = false;

        foreach ($answers as $answer) {
            $question = $answer->question;
            if ($question && $question->getRawOriginal('expected_safe_answer') !== null) {
                $hasQuestionsWithSafeAnswers = true;
                $expected = $question->expected_safe_answer ? '1' : '0';
                if ($answer->answer_value === $expected) {
                    $safeAnswersCount++;
                    $answer->is_safe = true;
                } else {
                    $unsafeAnswersCount++;
                    $answer->is_safe = false;
                }
            } else {
                $answer->is_safe = null;
            }
        }

        if ($unsafeAnswersCount > 0) {
            $safetyStatus = 'unsafe';
        } elseif ($hasQuestionsWithSafeAnswers && $safeAnswersCount > 0) {
            $safetyStatus = 'safe';
        } else {
            $safetyStatus = 'unknown';
        }

        $unansweredQuestions = Question::query()
            ->with('questionType:id,name,slug')
            ->whereDoesntHave('answers', function ($q) use ($organizationalUnit) {
                $q->where('office_id', $organizationalUnit->id);
            })
            ->orderBy('sort')
            ->orderBy('id')
            ->get();

        $canSubmitUnitQuestionnaire = $organizationalUnit->userCanSubmitQuestionnaire($request->user());

        return view('organizational-units.show', compact(
            'organizationalUnit',
            'safetyStatus',
            'answers',
            'unansweredQuestions',
            'canSubmitUnitQuestionnaire',
        ));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(OrganizationalUnit $organizationalUnit)
    {
        $unitTypes = UnitType::all();
        $parentUnits = OrganizationalUnit::where('id', '!=', $organizationalUnit->id)->with('unitType')->get();
        return view('organizational-units.edit', compact('organizationalUnit', 'unitTypes', 'parentUnits'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, OrganizationalUnit $organizationalUnit)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'parent_id' => 'nullable|exists:organizational_units,id',
            'unit_type_id' => 'required|exists:unit_types,id',
        ];

        $validatedData = $request->validate($rules);

        $organizationalUnit->update($validatedData);

        Alert::success('نجاح', 'تم تحديث الوحدة التنظيمية بنجاح!');
        return redirect()->route('organizational-units.index');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(OrganizationalUnit $organizationalUnit)
    {
        $organizationalUnit->delete();

        Alert::success('نجاح', 'تم حذف الوحدة التنظيمية بنجاح!');
        return redirect()->route('organizational-units.index');
    }
}
