<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\JobPackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PackageController extends Controller
{
    public function index()
    {
        $packages = JobPackage::where('ppk_id', Auth::id())->paginate(10);
        return view('packages.index', compact('packages'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'job_type' => 'required|string',
            'sub_classification' => 'required|string',
            'budget' => 'required|numeric',
            'province' => 'required|string',
            'regency' => 'required|string',
            'district' => 'required|string',
            'village' => 'required|string',
            'duration_days' => 'required|integer',
            'description' => 'nullable|string',
        ]);

        $validated['ppk_id'] = Auth::id();
        $validated['status'] = 'draft';

        JobPackage::create($validated);

        return redirect()->route('ppk.packages.index')->with('success', 'Paket berhasil dibuat!');
    }

    public function show(JobPackage $package)
    {
        return view('packages.show', compact('package'));
    }

    public function edit(JobPackage $package)
    {
        return view('packages.edit', compact('package'));
    }

    public function update(Request $request, JobPackage $package)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'job_type' => 'required|string',
            'sub_classification' => 'required|string',
            'budget' => 'required|numeric',
            'province' => 'required|string',
            'regency' => 'required|string',
            'district' => 'required|string',
            'village' => 'required|string',
            'duration_days' => 'required|integer',
            'description' => 'nullable|string',
        ]);

        $package->update($validated);

        return redirect()->route('ppk.packages.index')->with('success', 'Paket berhasil diupdate!');
    }

    public function destroy(JobPackage $package)
    {
        $package->delete();
        return redirect()->route('ppk.packages.index')->with('success', 'Paket berhasil dihapus!');
    }
}