<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Models\Sprint;
use App\Models\Project;
use App\Models\Requirement;
use Illuminate\Http\Request;
use App\Models\ProjectSprint;
use App\Models\SprintBacklog;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\ProjectResource;
use App\Models\NonFunctionalRequirement;
use App\Http\Resources\RequirementResource;
use App\Http\Resources\ProjectSprintResource;
use App\Http\Resources\SprintBacklogResource;
use App\Http\Requests\StoreRequirementRequest;
use App\Http\Requests\UpdateRequirementRequest;
use App\Http\Resources\NonFunctionRequirementResource;
use App\Http\Resources\ProjectSprintForBacklogResource;

class ProductBacklogController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();

        $requirementsQuery = Requirement::with(['project', 'sprints']);

        if ($user->role !== 'admin') {
            // Normal users only see requirements of projects they are assigned to
            $requirementsQuery->whereHas('project.users', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            });
        }

        return Inertia::render('product-backlogs/Index', [
            'product_backlogs' => RequirementResource::collection(
                $requirementsQuery->orderBy('project_id')->paginate(10)
            ),
            'breadcrumbs' => [
                ['title' => 'Product Backlogs', 'href' => '/product-backlogs'],
            ],
        ]);
    }


    /**
     * Display non-functional requirements listing.
     */
    public function nfr()
    {
        $user = Auth::user();

        $nfrQuery = NonFunctionalRequirement::with('project');

        if ($user->role !== 'admin') {
            // Normal users only see NFRs for projects they are assigned to
            $nfrQuery->whereHas('project.users', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            });
        }

        return Inertia::render('product-backlogs/Nfr', [
            'product_backlogs' => NonFunctionRequirementResource::collection(
                $nfrQuery->orderBy('project_id')->paginate(10)
            ),
            'breadcrumbs' => [
                ['title' => 'Product Backlogs', 'href' => '/product-backlogs'],
                ['title' => 'Non Functional Requirement', 'href' => '/product-backlogs/non-functional-requirements'],
            ],
        ]);
    }

    /**
     * Display non-functional requirements listing.
     */
    public function sprintBacklogs()
    {
        $user = Auth::user();

        $projectSprintsQuery = ProjectSprint::with(['project', 'sprint'])
            ->orderByDesc('updated_at');

        if ($user->role !== 'admin') {
            // Normal users only see sprints for projects they are assigned to
            $projectSprintsQuery->whereHas('project.users', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            });
        }

        $projectSprints = $projectSprintsQuery->paginate(10);

        return Inertia::render('product-backlogs/Sprint-backlogs', [
            'sprint_backlogs' => ProjectSprintResource::collection($projectSprints),
            'breadcrumbs' => [
                ['title' => 'Product Backlogs', 'href' => '/product-backlogs'],
                ['title' => 'Sprint Backlogs', 'href' => '/product-backlogs/sprint-backlogs'],
            ],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $projects = Project::where('status', 'requirement change')
            ->with(['sprints:id,name']) // eager load only needed fields
            ->get(['id', 'name', 'status']);

        return Inertia::render('product-backlogs/Requirement-create', [
            'projects' => ProjectSprintForBacklogResource::collection($projects),
            'breadcrumbs' => [
                [ 'title' => 'Product Backlogs', 'href' => '/product-backlogs' ],
                [ 'title' => 'Create Sprint Backlog', 'href' => '/product-backlogs/sprint-backlogs/create' ],
            ],
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreRequirementRequest $request)
    {
        $validated = $request->validated();

        // 1️⃣ Create the Requirement
        $requirement = Requirement::create([
            'name'        => $validated['name'],
            'description' => $validated['description'],
            'project_id'  => $validated['project_id'],
            'weight'      => 0.00,
        ]);

        // 2️⃣ Build SprintBacklog rows using relationship
        $rows = $requirement->project
            ->nonFunctionalRequirements
            ->map(fn ($nfr) => [
                'nfu_id'     => $nfr->id,
                'project_id' => $requirement->project_id,
                'sprint_id'  => $validated['sprint_id'],
                'status'     => 'pending',
            ])
            ->toArray();

        // 3️⃣ Attach SprintBacklogs via requirement relationship
        $requirement->sprintBacklogs()->createMany($rows);

        return redirect()
            ->route('product-backlogs.index')
            ->with('success',);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRequirementRequest $request, string $id)
    {
        //
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }
        $requirement = Requirement::findOrFail($id);
        $validated = $request->validated();

        $requirement->update([
            'name'        => $validated['name'],
            'description' => $validated['description'] ?? $requirement->description,
        ]);
        
        return redirect()->back()->with('success');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $project = Requirement::findOrFail($id);

        $project->delete();

        return redirect()->back()->with('success');

    }
}
