<?php

namespace Mtc\Modules\BasketRecovery\Classes;

use Illuminate\Database\Eloquent\Model;
use Order;
/**
 * BasketRecoveryLog class
 *
 * This eloquent model provides the connection to any logs
 * (used for statistics)
 *
 * @author  Craig McCreath <craig.mccreath@mtcmedia.co.uk>
 */
class BasketRecoveryLog extends Model
{
    // Columns permitted to be mass assigned
    protected $fillable = [
        'basket_recovery_id',
        'basket_id',
        'action',
        'value'
    ];

    public $timestamps = true;

    /**
     * Track an order
     *
     * This is used alongside the hook in this modules loader.php
     * to see if we need to contribute an order to a particular
     * recovery email
     * 
     * @param  Order  $order
     * @return bool
     */
    public static function trackOrder(Order $order)
    {
        $log = self::query()
            ->where('basket_id', '=', $order->getBasketId())
            ->orderBy('id', 'DESC')
            ->first();

        if (empty($log->basket_recovery_id)) {
            return false;
        }

        $data = [
            'basket_recovery_id' => $log->basket_recovery_id,
            'basket_id' => $order->getBasketId(),
            'action' => 'sale',
            'value' => $order->getId()
        ];

        return self::query()
            ->create($data);
    }
}
