<?php

namespace MtcPharmacy\Subscriptions\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Mtc\Shop\Item;
use MtcPharmacy\Subscriptions\Classes\Subscription;
use MtcPharmacy\Subscriptions\Classes\SubscriptionPreference;


class SubscriptionPreferencesController extends \App\Http\Controllers\Controller
{

    public function update(Request $request)
    {
        $input_data = $request->input('data');

        foreach ($input_data as $line) {

            $sp = SubscriptionPreference::query()
                ->where('item_id', $line['item_id'])
                ->where('item_size_id', $line['item_size_id'])
                ->first()
            ;

            if ($sp) {
                $safeData = collect((array) $line)->only($sp->getFillable())->toArray();

                if ($line['item_size_id'] == null) {
                    $item = Item::query()->where('id', $line['item_id'])->first();
                    $item->update([
                        'subscription_is_allowed' => (bool) ($line['is_allowed'] ?? false),
                        'subscription_can_be_paused' => (bool) ($line['can_be_paused'] ?? false),
                        'subscription_max_number_of_issues' => $line['max_number_of_issues'] ?? null,
                    ]);
                }

                $sp->update($safeData);
            }
        }

        return [
            'success' => true,
        ];
    }


    public function get_data($item_id, Request $request)
    {
        SubscriptionPreference::ensureItemPreferencesExist($item_id);

        $subscription_preferences = SubscriptionPreference::query()
            ->with('shop_item')
            ->with('shop_item_size')
            ->where('item_id', $item_id)
            ->orderBy('item_size_id', 'asc')
            ->get()
        ; 

        return [
            'data' => $subscription_preferences,
            'allowed_intervals' => Subscription::get_allowed_intervals(),
        ];
    }

}



