<?php

namespace App\Http\Controllers;

use App\Models\Policy;
use App\Http\Requests\StorePolicyRequest;
use App\Http\Requests\UpdatePolicyRequest;
use App\Models\PolicyCategory;

class PolicyController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $policies = Policy::orderBy('created_at', 'desc')->with('category')->get();
        $policyCategories = PolicyCategory::all();
        return view('admin.policy.index', compact('policies', 'policyCategories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

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

        Policy::create($data);
        return redirect()->route('policies.index')->with('success', 'Policy added successfully!');
    }

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

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Policy $policy)
    {
        $policyCategories = PolicyCategory::all();
        return view('admin.policy.edit', compact('policy', 'policyCategories'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdatePolicyRequest $request, Policy $policy)
    {
        $data = $request->validated();

        $policy->update($data);
        return redirect()->route('policies.index')->with('success', 'Policy updated successfully');
    }

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