<?php
/**
 *
 * scheduled task to store member specific
 * complimented items data in a table to prevent getting all
 * the member info on the fly as it would
 * slow down the website
 *
 * Cron job should be set to run no more than twice a day!
 *
 */

use Illuminate\Database\Eloquent\Builder;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\ComplimentedItems\Classes\MemberItemPreference;

chdir(dirname(__FILE__));
$path = '../../../';
define('LOCK_FILE', __FILE__.'.lock');

require_once $path.'core/includes/header.inc.php';
require_once 'lock_controller.php';


// delete all from the members_items_preferences table
MemberItemPreference::query()
    ->truncate();

\Mtc\Shop\Order\Item::query()
    ->with('item.categories')
    ->with('item.brands')
    ->with('order')
    ->where('order.paid', 1)
    ->get()
    ->each(function (\Mtc\Shop\Order\Item $orderItem) {
        $categoryID = 0;
        $brandID = 0;
        if (empty($orderItem->item)) {
            if ($brand = $orderItem->item->brands->first()) {
                $brandID = $brand->id;
            }
            if ($category = $orderItem->item->categories->first()) {
                $categoryID = $category->id;
            }
        }
        MemberItemPreference::query()
            ->create([
                'member_id' => $orderItem->order->member,
                'item_id' => $orderItem->item_id,
                'brand_id' => $brandID,
                'category_id' => $categoryID,
            ]);
    });