<?php

namespace App\Models;
use App\Models\BaseModel;
class CounterModel extends BaseModel {
  protected $table      = 'counter';
  protected $primaryKey = 'CounterID';
  protected $allowedFields = ['CounterValue', 'CounterStart', 'CounterEnd', 'CounterReset', 'CounterName', 'CreateDate', 'EndDate']; 
	
	protected $useTimestamps = true;
	protected $createdField = "CreateDate";
	protected $updatedField = "";
	protected $useSoftDeletes = true;
	protected $deletedField = "EndDate";

  public function use($CounterID) {
		$row = $this->where('CounterID',$CounterID)->get()->getResultArray();	
		$cValue = $row[0]['CounterValue'];
		$cStart = $row[0]['CounterStart'];
		$cEnd = $row[0]['CounterEnd'];
		//$cReset = $row[0]['CounterReset'];
		$cPad = strlen((string)$cEnd);
    // next value > end, back to start
		if($cValue > $cEnd) { $cValue = $cStart; }
		$cnum = str_pad($cValue, $cPad, "0", STR_PAD_LEFT); 
		$cValue_next = $cValue+1;
		$this->set('CounterValue', $cValue_next)->where('CounterID',$CounterID)->update();
		return $cnum;
	}

}
