<?php

namespace App\Http\Controllers\Treatment;

use App\Http\Controllers\Controller;
use App\Models\TreatmentPlanItems;
use App\Models\TreatmentPlans;
use Illuminate\Http\Request;

class TreatmentPlanItemController extends Controller
{
    public function store(Request $request, $plan_id)
    {
        $plan = TreatmentPlans::findOrFail($plan_id);

        $data = $request->validate([
            'service_id' => 'nullable|exists:services,id',
            'visit_id'   => 'nullable|exists:visits,id',
            'tooth_number' => 'nullable|string|max:10',
            'surface'      => 'nullable|string|max:20',
            'quantity'     => 'required|integer|min:1',
            'price'        => 'required|numeric|min:0',
            'discount'     => 'nullable|numeric|min:0',
            'status'       => 'required|in:planned,in_progress,done,cancelled',
            'notes'        => 'nullable|string',
        ]);

        $data['treatment_plan_id'] = $plan->id;

        TreatmentPlanItems::create($data);

        return back()->with('success', 'تم إضافة البند بنجاح');
    }

    public function updateStatus(Request $request, $id)
    {
        $item = TreatmentPlanItems::findOrFail($id);

        $data = $request->validate([
            'status' => 'required|in:planned,in_progress,done,cancelled',
        ]);

        $item->status = $data['status'];
        $item->save();

        return back()->with('success', 'تم تحديث حالة البند بنجاح.');
    }


    public function destroy($id)
    {
        $item = TreatmentPlanItems::findOrFail($id);
        $item->delete();

        return back()->with('success', 'تم حذف البند');
    }
}
