<?php

namespace App\Service;
use DB;
use App\Models\User;
use App\Models\SequenceFormat;
use Validator;
use Auth;

class SequenceService
{
    public function updateSequence($module){

        //quotation , sale_order , delivery_challan , invoice , credit_note, payment_receipt,
        // purchase_order, bill , debit_note , payment_made ,expenses , grn 
        //accounts , journal
        //production_order, workstation
        //dsr ,mice
                                            
        try{
    
            $sequence=SequenceFormat::where('module',$module)->firstOrFail();

            if($sequence!=null){

                // 1: Auto generate, 2:Manual Sequence
                if($sequence['sequence_type'] ==1){

                    // Pad the sequence number
                    // $paddedSequence = str_pad($validatedData['sequence_number'], $validatedData['padded_digits'], '0', STR_PAD_LEFT);

                    // Generate the sequence
                    // $newSequence = $validatedData['prefix'] . $validatedData['delimiter'] . $paddedSequence;

                    // Update Sequence
                    $sequence['sequence_number']=intval($sequence['sequence_number'])+1;
                    $sequence->save();
                }
            }

        }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

            // Return error message in JSON if ID not found
            return false;
        }
        
        return true;
        
    }

    public function getSequence($module)
    {
        try {
            $validatedData = SequenceFormat::where('module', $module)->firstOrFail();

            $sequenceNumber = (int) $validatedData['sequence_number'];
            $paddedDigits = (int) ($validatedData['padded_digits'] ?? 0); // default to 0 if null

            // Pad the sequence number safely
            $paddedSequence = str_pad($sequenceNumber, $paddedDigits, '0', STR_PAD_LEFT);

            // Generate the final sequence string
            $newSequence = $validatedData['prefix'] . $validatedData['delimiter'] . $paddedSequence;

            //Also update sequence with the new value
            $validatedData['sequence_number'] = $sequenceNumber + 1;
            $validatedData->save();

            return $newSequence;

        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            // Return null if no format found for the given module
            return null;
        }
    }

    // Delete data than update sequence
    public function deleteSequence($module){
        $sequence=SequenceFormat::where('module',$module)->firstOrFail();
        $sequence['sequence_number']=intval($sequence['sequence_number'])-1;
        $sequence->save();

        return true;
    }

}