<?php

namespace Modules\Admin\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Main\Models\Complex;
use Modules\Plan7\Models\ComplexPlan7;
use Modules\Main\Models\Design;


class AdminPlan7Controller extends Controller
{
    public function index()
    {
        return view('admin::plan7.index', [
            'complexes' => Complex::orderBy('city_id')->get()
        ]);
    }

    public function save(Request $request)
    {
        foreach ($request->complexes as $complexId => $plan7ApiData) {
            if ($plan7ApiData['token'] && $plan7ApiData['zk']) {
                ComplexPlan7::updateOrCreate([
                    'complex_id' => $complexId,
                ], [
                    'complex_id' => $complexId,
                    'token' => $plan7ApiData['token'],
                    'zk' => $plan7ApiData['zk']
                ]);
            } else {
                ComplexPlan7::where('complex_id', $complexId)->delete();
            }
        }
        if ($request->has('plan7_iframe')) {
            if (!$request->plan7_iframe) {
                Design::where('parameter', 'plan7_iframe')->delete();
            } else {
                Design::updateOrCreate([
                    'parameter' => 'plan7_iframe',
                    'value' => $request->plan7_iframe
                ]);
            }
        }
        return to_route('admin.plan7');
    }
}