<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class SequenceHelper
{
    /**
     * Get the Financial Year prefix (e.g., "2526" for FY 2025-2026)
     * FY starts on April 1st.
     */
    public static function getFyPrefix($date = null)
    {
        $date = $date ? Carbon::parse($date) : Carbon::now();
        $year = $date->year;
        $month = $date->month;

        if ($month < 4) {
            // Jan-Mar: FY is PreviousYear-CurrentYear (e.g., Jan 2026 -> 2526)
            $startYear = $year - 1;
            $endYear = $year;
        } else {
            // Apr-Dec: FY is CurrentYear-NextYear (e.g., Apr 2025 -> 2526)
            $startYear = $year;
            $endYear = $year + 1;
        }

        // Format: YYyy (e.g., 2526)
        return substr($startYear, -2) . substr($endYear, -2);
    }

    /**
     * Generate the next sequence number in format: [PREFIX-]{FY}-{SEQ}
     * If prefix is empty, format is {FY}-{SEQ}
     * 
     * @param string $modelClass The Eloquent model class name
     * @param string $column The column to check for sequence
     * @param string $fyPrefix The Financial Year prefix (e.g. "2526")
     * @param string $staticPrefix Optional static prefix (e.g. "INV", "R")
     * @param int $padding Length of the sequence number (default 4)
     * @param int $offset Offset to add to the next sequence (default 0)
     * @return string
     */
    public static function generateNextSequence($modelClass, $column, $fyPrefix, $staticPrefix = '', $padding = 4, $offset = 0)
    {
        // Construct the search prefix
        // Pattern: {staticPrefix}-{fyPrefix}-  OR {fyPrefix}-
        // Note: staticPrefix might have a separator built-in or we add it?
        // Let's assume staticPrefix does NOT have separator, we add '-' if present.

        $searchPrefix = '';
        if ($staticPrefix) {
            $searchPrefix .= $staticPrefix . '-';
        }
        $searchPrefix .= $fyPrefix . '-';

        // Find last record matching this prefix
        $lastRecord = $modelClass::where($column, 'like', $searchPrefix . '%')
            ->orderByRaw("LENGTH($column) DESC") // Ensure we compare similarly sized strings first (optional, but good)
            ->orderBy($column, 'desc')
            ->first();

        if (!$lastRecord) {
            return $searchPrefix . str_pad(1 + $offset, $padding, '0', STR_PAD_LEFT);
        }

        // Extract sequence part
        // Value: PREFIX-2526-0001
        // SearchPrefix: PREFIX-2526-
        $value = $lastRecord->$column;
        $sequencePart = substr($value, strlen($searchPrefix));

        if (!is_numeric($sequencePart)) {
            // Fallback if parsing failed (e.g. if suffix exists)
            return $searchPrefix . str_pad(1 + $offset, $padding, '0', STR_PAD_LEFT);
        }

        $nextSeq = (int) $sequencePart + 1 + $offset;
        return $searchPrefix . str_pad($nextSeq, $padding, '0', STR_PAD_LEFT);
    }
}
