<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;  // ✅ اضافه کن
use Illuminate\Http\Request;
use App\Models\Formula;
use App\Models\Test;

class AdminFormulaController extends Controller
{
    public function index($id)
    {
       $test=Test::findOrFail($id);
       $formulas=Formula::where('test_id',$id)->get();
       return view('admin.formulas.index', compact('test','formulas'));

    }

    public function create($id)
    {
        $test = Test::findOrFail($id);
        return view('admin.formulas.create', compact('test'));
   }

    public function store(Request $request,$id)
    {
        $test=Test::findOrFail($id);
        $validated = $request->validate([
            //'test_id'            => 'required',
            'name'               => 'required|string|max:255',
            'formula_expression' => 'required|string|max:255',
            'formula_config'     => 'required|string|max:255',
            'is_active'          => 'required|boolean',]);
        Formula::create([
            'test_id' => $id,  // ✅ از Route
            'name' => $validated['name'],  // ✅ از validated استفاده کن
            'formula_expression' => $validated['formula_expression'],
            'formula_config' => $validated['formula_config'],  // ✅ بدون json_decode (اگر ستون text است)
            'is_active' => $validated['is_active'] ?? true,

        ]);

        return redirect()->route('admin.formulas.index',$id)->with('success', 'Formula saved successfully ✅');
    }

    public function edit($id,$fid)
    {
        $test=Test::findOrFail($id);
        $formula=Formula::where('test_id',$fid);
        return view('admin.formulas.edit', compact('test','formula'));
    }

    public function update(Request $request, $id,$fid)
    {
        $test=Test::findOrFail($id);
        $formula=Formula::where('test_id',$id)->findOrFail($fid);
        $validated = $request->validate([
            //'test_id'            => 'required',
            'name'               => 'required|string|max:255',
            'formula_expression' => 'required|string|max:255',
            'formula_config'     => 'required|string|max:255',
            'is_active'          => 'nullable|boolean',]);
        //Formula::delete();
        $formula->update([
            'test_id' => $id,  // ✅ از Route
            'name' => $validated['name'],  // ✅ از validated استفاده کن
            'formula_expression' => $validated['formula_expression'],
            'formula_config' => $validated['formula_config'],  // ✅ بدون json_decode (اگر ستون text است)
            'is_active' => $validated['is_active'] ?? false,
        ]);
    return redirect()->route('admin.formulas.index',$id)->with('success', 'Formula updated successfully');
}
public function destroy($id,$fid){
    $formula = Formula::where('test_id', $id)
    ->findOrFail($fid);
    $formula->delete();
    return redirect()->route('admin.formulas.index',$id)->with('success', 'Formula deleted successfully');

}

}
