<?php

namespace App\Modules\Bookings\Traits;

use Illuminate\Support\Facades\Auth;
use App\Exceptions\PermissionDeniedException;
use App\Models\StatusChange;
use App\Models\AssignedChange;

trait TaskAutomationTrait
{
    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     */
    public static function bootTaskAutomationTrait()
    {
        static::creating(function ($model) {
            if ($model->return_id == '') {
                $model->return_id = null;
            }
            if ($model->booking_fee_id == '') {
                $model->booking_fee_id = null;
            }
            $model->created_by = getAuthUserId();
            $model->updated_by = getAuthUserId();
        });

        static::created(function ($model) {
             switch ($model->type) {
                case 'followup':
                    $model->suggestFollowupUser();
                    break;

                case 'qa':
                    $model->suggestQAUser();
                    break;

                default:
                    $model->suggestUser();
                    break;
            }

        });

        static::updating(function ($model) {
            // Store the user id that modified the task
            $model->updated_by = getAuthUserId();

            // Get all the dirty attributes
            $dirty = $model->getDirty();

            // Check to see if the status has been updated and store a new entry in the database
            // We need to keep records of this as it is useful to trace back
            // who did what & for statistics purposes
            if (isset($model->original['status_id']) && $model->original['status_id'] != $model->status_id) {
                $status = StatusChange::create([
                    'related_id'   => $model->id,
                    'related_type' => 'task',
                    'old_status'   => $model->original['status_id'],
                    'new_status'   => $model->status_id,
                ]);

                if (! $status) {
                    return false;
                }
            }

            // Check to see if the task has been reassigned from one user to another and store a new entry in the database
            // We need to keep records of this as it is useful to trace back
            // who did what & for statistics purposes
            if (isset($dirty['assigned_to']) && $model->getOriginal('assigned_to') != $model->assigned_to) {
                $change = AssignedChange::create([
                    'related_id'   => $model->id,
                    'related_type' => 'task',
                    'old_user'     => isset($model->original['assigned_to']) ? $model->original['assigned_to'] : null,
                    'new_user'     => $model->assigned_to,
                ]);

                if (! $change) {
                    return false;
                }
            }

            // We are checking to see if the task is a remote support OR onsite
            // and if so then only people in the accounts group are able to update
            // the invoice number or to mark it as paid...
            // A permission denied exception will be thrown if the user doesn't have access
            if (($model->type == 'support' || $model->type == 'onsite') && $model->invoice_number != 1) {
                if ((isset($dirty['invoiced']) || isset($dirty['invoice_number']) || isset($dirty['paid']))
                        && ! Auth::user()->isMemberOf(5)) {
                    // The user tried to mark this as invoiced but he is not part of the accounts group
                    throw new PermissionDeniedException();
                }
            }

            if (isset($model->original['paid_at']) && ! $model->original['paid_at'] && $model->paid_at) {
                $model->paid = 1;
            }
            if (isset($model->original['paid']) && ! $model->original['paid'] && $model->paid && ! $model->paid_at) {
                $model->paid_at = date('Y-m-d H:i:s');
            }
            if (! $model->paid_at && $model->paid) {
                $model->paid = 0;
            }

            if ($model->invoice_number) {
                $model->invoiced = 1;
            } elseif ($model->invoiced == 1 && ! $model->invoice_number) {
                $model->invoiced = 0;
            }
            if (isset($model->original['invoiced']) && ! $model->original['invoiced'] && $model->invoiced == 1) {
                $model->invoiced_at = date('Y-m-d H:i:s');
            }

        });
    }
}
