<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;

class AutoNumbering
{

    function __construct($params){
        $this->type = @$params["type"];
        $this->prefix = @$params["prefix"];
        $this->location_id = (int) @$params["location_id"];
        $this->pad = @$params["pad"] ?? 12;
    }

    function getCurrent(){

        $numbering = (array) @DB::select("SELECT id, transaction, location_id, prefix, pad, current
            FROM numbering
            WHERE transaction = ? AND location_id = ?
            FOR UPDATE
        ", [$this->type, $this->location_id])[0];

        if ($numbering == null) {
            $numbering = DB::table("numbering")->insert([
                "transaction" => $this->type,
                "location_id" => $this->location_id,
                "prefix" => $this->prefix,
                "pad" => $this->pad,
                "current" => 0
            ]);

            $numbering = (array)  DB::select("SELECT id, transaction, location_id, prefix, pad, current
            FROM numbering
                WHERE id = ?
                FOR UPDATE
            ", [DB::getPdo()->lastInsertId()])[0];
        }

        $prefix_number = $numbering["prefix"];
        $next_number = $numbering["current"] + 1;
        $pad_number = $numbering["pad"] - strlen($prefix_number);
        $number = $prefix_number . str_pad($next_number, $pad_number, 0, STR_PAD_LEFT);

        $this->id = $numbering["id"];

        DB::statement("UPDATE numbering SET current = current+1 WHERE id = ?", [$this->id]);

        return $number;
    }
}
