<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\DocumentSequence;
use App\Models\FinancialYear;
use App\Services\AuditLogService;
use Illuminate\Http\Request;

class DocumentSequenceController extends Controller
{
    public function index()
    {
        $sequences = DocumentSequence::with(['branch', 'financialYear'])->get();
        $branches = Branch::where('status', 'active')->get();
        $years = FinancialYear::all();

        return view('settings.document_sequences.index', compact('sequences', 'branches', 'years'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'sequence_type' => 'required|string|max:100',
            'prefix' => 'nullable|string|max:20',
            'starting_number' => 'required|integer|min:1',
            'next_number' => 'required|integer|min:1',
            'digit_length' => 'required|integer|min:3|max:12',
            'branch_id' => 'nullable|exists:branches,id',
            'financial_year_id' => 'nullable|exists:financial_years,id',
        ]);

        $seq = DocumentSequence::create($validated);

        AuditLogService::log('DOCUMENT_SEQUENCE_CREATED', 'DocumentSequence', $seq->id, null, $seq->toArray());

        return redirect()->route('document-sequences.index')->with('success', 'Document sequence configured successfully.');
    }

    public function update(Request $request, DocumentSequence $documentSequence)
    {
        $validated = $request->validate([
            'prefix' => 'nullable|string|max:20',
            'starting_number' => 'required|integer|min:1',
            'next_number' => 'required|integer|min:1',
            'digit_length' => 'required|integer|min:3|max:12',
            'branch_id' => 'nullable|exists:branches,id',
            'financial_year_id' => 'nullable|exists:financial_years,id',
        ]);

        $oldData = $documentSequence->toArray();
        $documentSequence->update($validated);

        AuditLogService::log('DOCUMENT_SEQUENCE_UPDATED', 'DocumentSequence', $documentSequence->id, $oldData, $documentSequence->fresh()->toArray());

        return redirect()->route('document-sequences.index')->with('success', 'Document sequence updated successfully.');
    }
}
