<?php

namespace MtcPharmacy\OutOfStockNotify\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use MtcPharmacy\OutOfStockNotify\Classes\OutOfStockNotification;
use Mtc\Shop\Item as ShopItem;


/**
 * Examples:
 *     php artisan send_back_in_stock_notifications
 */

class SendBackInStockNotificationsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send_back_in_stock_notifications';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send back-in-stock notifications.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // Prevent multiple instances of the task.
        $results = (array)DB::select( DB::raw("SELECT GET_LOCK('back_in_stock_notifications', 5) AS has_obtained_lock") );
        if ($results && ! $results[0]->has_obtained_lock) {
            exit();
        }

        $this->info(__METHOD__);

        $pending_notifications = OutOfStockNotification::pending()
            ->groupBy('item_id')
            ->get()
        ;

        foreach ($pending_notifications as $pending_notification) {
            if ($pending_notification->item->isInStock()) {
                $this->sendTheNotificationsForItem($pending_notification->item);
            }
        }

        $this->info('Done.');
    }



    /*** HELPERS ***/

    private function sendTheNotificationsForItem(ShopItem $shop_item)
    {
        $twig = app('twig');

        $notifications_to_send = OutOfStockNotification::pending()
            ->where('item_id', $shop_item->id)
            ->get()
        ;

        $site_config = get_site_config();

        $email_subject = 'Product back in stock';
        $email_body = $twig->render('emails/shop/back_in_stock.twig', [
            'out_of_stock_notification_item' => [
                'name' => $shop_item->name ?? '-',
                'url' => $site_config['SITE_URL'] . ($shop_item->url ?? null),
            ],
            'site_config' => $site_config,
        ]);

        foreach ($notifications_to_send as $notification) {
            echo "Sending to [{$notification->email}].\n";

            $params = [];

            if (DEV_MODE) {
                $params['bcc'] = DEV_EMAIL;
            } else {
                $params['bcc'] = config('site.shop_email');
            }

            $sent_count = email($notification->email, $email_subject, $email_body, $params);

            if ($sent_count) {
                $notification->markNotified();
            }
        }
    }

}
