<?php

namespace App\Http\Controllers\Admin;

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

class OPDController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $opds = OPD::withCount('responses')->orderBy('name')->get();
        return view('admin.opds.index', compact('opds'));
    }

    public function create()
    {
        return view('admin.opds.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:opds,code',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        OPD::create([
            'name' => $request->name,
            'code' => strtoupper($request->code),
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil ditambahkan.');
    }

    public function show($id)
    {
        $opd = OPD::withCount('responses')->findOrFail($id);
        return view('admin.opds.show', compact('opd'));
    }

    public function edit($id)
    {
        $opd = OPD::findOrFail($id);
        return view('admin.opds.edit', compact('opd'));
    }

    public function update(Request $request, $id)
    {
        $opd = OPD::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:opds,code,' . $id,
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $opd->update([
            'name' => $request->name,
            'code' => strtoupper($request->code),
            'description' => $request->description,
            'is_active' => $request->has('is_active'),
        ]);

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $opd = OPD::findOrFail($id);
        
        // Check if OPD is being used
        if ($opd->responses()->count() > 0) {
            return redirect()->route('admin.opds.index')
                ->with('error', 'OPD tidak dapat dihapus karena sedang digunakan dalam response.');
        }

        $opd->delete();

        return redirect()->route('admin.opds.index')
            ->with('success', 'OPD berhasil dihapus.');
    }
}

