<?php

namespace App\Observers;

use App\Model\SaleDetailsModel;
use App\Model\SaleModel;
use App\Model\StockModel;
use App\Model\TrackStockModel;
use Auth;

class SalesObserver
{


    public function created(SaleModel $sale)
    {

    }

    public function updated(SaleModel $sale)
    {
            $sales = SaleDetailsModel::where('sale_id', $sale->id)->get();
            foreach ($sales as $row) {
                $stock = StockModel::where(['barcode' => $row->barcode, 'warehouse_id' => $sale->warehouse_id])->first();
                $edit = '';
                if($sale->isDirty('edited_at')){
                    $edit = 'Edited';
                }
                if($sale->isDirty('return_status')){
                    $edit = 'Returned';
                }
                if($sale->isDirty('status')){
                    if($sale->status==1){
                        $edit = 'Approved';
                    }
                    if($sale->status==2){
                        $edit = 'Rejected';
                    }

                }
                if ($row->status!==0) {
                    TrackStockModel::create([
                        'user_id' => Auth::user()->id,
                        'warehouse_id' => $sale->warehouse_id,
                        'ref_number' => $sale->invoice_number,
                        'ref_type' => ($sale->is_role==='out_shop'?'sale-request':'pos'),
                        'ref_id' => $sale->id,
                        'barcode' => $row->barcode,
                        'qty' => $row->qty,
                        'date' => now(),
                        'last_stock' => ($stock?$stock->stock_qty:0) + $row->qty,
                        'note' => $edit.' on '.($sale->is_role==='out_shop'?'Sale-request':'POS'),
                    ]);
                }
            }

    }

    public function deleted(SaleModel $sale)
    {
        //
    }

    public function restored(SaleModel $sale)
    {
        //
    }

    public function forceDeleted(SaleModel $sale)
    {
        //
    }
}
