<?php

namespace MtcPharmacy\OutOfStockNotify\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use MtcPharmacy\OutOfStockNotify\Classes\OutOfStockNotification;

class OutOfStockNotifyController extends Controller
{
    public function signup(Request $request)
    {
        $result = [
            'success' => [
                'message' => 'Saved.',
            ],
            'errors' => null,
        ];

        $item_id = (int) $request->input('item_id');
        $email = $request->input('email');

        $pending_notifications = OutOfStockNotification::pending()
            ->where('email', $email)
            ->where('item_id', $item_id)
            ->count();

        if (! $pending_notifications) {
            $notification = new OutOfStockNotification;
            $notification->item_id = request()->input('item_id');
            $notification->email = request()->input('email');

            $errors = $notification->validate();

            if (! $errors) {
                $notification->save();
            } else {
                $result['success']['message'] = 'Processed.';
                $result['errors'] = $errors;
            }
        } else {
            $result['success']['message'] = 'Thank you.';
        }

        return $result;
    }
}
