<?php

namespace App\Http\Controllers\Company\FixedAssets;

use App\Models\{AuditLog, FixedAssetDepreciation};
use App\Services\FixedAssetDepreciationService;
use App\Support\PayrollVoucherOptions;
use Illuminate\Http\Request;

class FixedAssetDepreciationController extends FixedAssetsBaseController
{
    public function __construct(private FixedAssetDepreciationService $service) {}

    public function index(Request $request)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('view');

        $cid = $this->companyId();
        $year = max(2000, min(2100, (int) $request->input('period_year', date('Y'))));
        $month = max(1, min(12, (int) $request->input('period_month', date('n'))));

        $schedule = $this->service->scheduleForPeriod($cid, $year, $month);

        $history = FixedAssetDepreciation::withoutGlobalScopes()
            ->where('company_id', $cid)
            ->where('period_year', $year)
            ->where('period_month', $month)
            ->with('asset')
            ->orderByDesc('posted_at')
            ->get();

        $totals = [
            'proposed' => round($schedule->where('can_post', true)->sum('proposed'), 2),
            'posted'   => round($history->sum('amount'), 2),
        ];

        return view('fixed-assets.depreciation.index', [
            'schedule'      => $schedule,
            'history'       => $history,
            'totals'        => $totals,
            'periodYear'    => $year,
            'periodMonth'   => $month,
            'periodLabel'   => PayrollVoucherOptions::periodLabel($year, $month),
            'years'         => PayrollVoucherOptions::years(),
            'months'        => PayrollVoucherOptions::months(),
        ]);
    }

    public function run(Request $request)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('edit');

        $validated = $request->validate([
            'period_year'  => 'required|integer|min:2000|max:2100',
            'period_month' => 'required|integer|min:1|max:12',
            'asset_ids'    => 'nullable|array',
            'asset_ids.*'  => 'integer',
        ]);

        $assetIds = array_values(array_unique(array_filter(array_map('intval', (array) ($validated['asset_ids'] ?? [])))));

        $result = $this->service->run(
            $this->companyId(),
            (int) $validated['period_year'],
            (int) $validated['period_month'],
            $assetIds !== [] ? $assetIds : null,
        );

        AuditLog::record(
            'create',
            'fixed_asset_depreciations',
            null,
            null,
            $result,
            'Depreciation run for ' . PayrollVoucherOptions::periodLabel((int) $validated['period_year'], (int) $validated['period_month']),
        );

        return redirect()
            ->route('fixed-assets.depreciation.index', [
                'period_year'  => $validated['period_year'],
                'period_month' => $validated['period_month'],
            ])
            ->with('success', "Depreciation posted for {$result['posted']} asset(s). Total: {$result['total_amount']}");
    }
}
