<?php

namespace App\Services;

use App\Models\CustomerOpeningBalance;
use App\Models\SupplierOpeningBalance;
use App\Models\Customer;
use App\Models\Supplier;
use App\Models\FinancialYear;
use App\Services\DocumentSequenceService;
use App\Services\AuditLogService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class OpeningBalanceService
{
    protected DocumentSequenceService $sequenceService;
    protected AuditLogService $auditService;

    public function __construct(DocumentSequenceService $sequenceService, AuditLogService $auditService)
    {
        $this->sequenceService = $sequenceService;
        $this->auditService    = $auditService;
    }

    public function createCustomerOpeningBalance(Customer $customer, array $data): CustomerOpeningBalance
    {
        return DB::transaction(function () use ($customer, $data) {
            $reference = $this->sequenceService->getNextNumber('OPENING_CUSTOMER')
                ?? ('OPEN-CUS-' . str_pad($customer->id, 4, '0', STR_PAD_LEFT));

            $balance = CustomerOpeningBalance::create([
                'customer_id'      => $customer->id,
                'financial_year_id'=> $data['financial_year_id'],
                'opening_date'     => $data['opening_date'],
                'reference'        => $reference,
                'amount'           => $data['amount'],
                'type'             => $data['type'] ?? 'receivable',
                'status'           => 'approved',
                'created_by'       => Auth::id(),
                'notes'            => $data['notes'] ?? null,
            ]);

            $this->auditService->log('OPENING_BALANCE_CREATED', 'customer_opening_balances', $balance->id, null, $balance->toArray());

            return $balance;
        });
    }

    public function createSupplierOpeningBalance(Supplier $supplier, array $data): SupplierOpeningBalance
    {
        return DB::transaction(function () use ($supplier, $data) {
            $reference = $this->sequenceService->getNextNumber('OPENING_SUPPLIER')
                ?? ('OPEN-SUP-' . str_pad($supplier->id, 4, '0', STR_PAD_LEFT));

            $balance = SupplierOpeningBalance::create([
                'supplier_id'      => $supplier->id,
                'financial_year_id'=> $data['financial_year_id'],
                'opening_date'     => $data['opening_date'],
                'reference'        => $reference,
                'amount'           => $data['amount'],
                'type'             => $data['type'] ?? 'payable',
                'status'           => 'approved',
                'created_by'       => Auth::id(),
                'notes'            => $data['notes'] ?? null,
            ]);

            $this->auditService->log('OPENING_BALANCE_CREATED', 'supplier_opening_balances', $balance->id, null, $balance->toArray());

            return $balance;
        });
    }
}
