<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Span;
use Illuminate\Http\Request;

class SpanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $q = $request->get('q');
        $status = $request->get('status');
        $spans = Span::query()
            ->search($q)
            ->status($status)
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('admin.spans.index', compact('spans', 'q', 'status'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.spans.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:100|unique:spans,code',
            'category' => 'nullable|string|max:100',
            'owner' => 'nullable|string|max:100',
            'status' => 'nullable|string|in:active,inactive,archived',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
            'notes' => 'nullable|string',
        ]);
        $validated['status'] = $validated['status'] ?? 'active';
        Span::create($validated);
        return redirect()->route('admin.spans.index')->with('success', 'Span created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(Span $span)
    {
        return view('admin.spans.show', compact('span'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Span $span)
    {
        return view('admin.spans.edit', compact('span'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Span $span)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:100|unique:spans,code,' . $span->id,
            'category' => 'nullable|string|max:100',
            'owner' => 'nullable|string|max:100',
            'status' => 'nullable|string|in:active,inactive,archived',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date',
            'notes' => 'nullable|string',
        ]);
        $validated['status'] = $validated['status'] ?? $span->status;
        $span->update($validated);
        return redirect()->route('admin.spans.index')->with('success', 'Span updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Span $span)
    {
        $span->delete();
        return redirect()->route('admin.spans.index')->with('success', 'Span deleted successfully');
    }
}