<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SubSystem;
use App\Models\Plan;
use App\Models\PlanItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class PlanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $result = SubSystem::with('items', 'plans.items.item')->orderBy('id')->get();

        return response()->json(['data' => $result], 200);
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $plan_id = Plan::create([
                'sub_system_id' => $request->sub_system_id,
                'name' => $request->name,
                'years' => $request->years,
                'price' => $request->price,
            ])->id;

            foreach ($request->items as $item) {
                PlanItem::create([
                    'plan_id' => $plan_id,
                    'item_id' => $item["id"],
                    'amount' => $item["amount"],
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $result = Plan::with('subsystem', 'items.item')->find($id);
        return response()->json(['data' => $result], 200);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Plan $plan)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        DB::beginTransaction();
        try {
            Plan::where('id', $id)->update([
                'name' => $request->name,
                'years' => $request->years,
                'price' => $request->price
            ]);

            foreach ($request->items as $item) {
                PlanItem::where('id', $item['id'])->update([
                    'amount' => $item['amount']
                ]);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        DB::beginTransaction();
        try {
            Plan::where('id', $id)->delete();
            PlanItem::where('plan_id')->delete();
            
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }
}
