<?php
namespace App\Http\Controllers;

use App\Models as M;
use App\Services\DepreciationService;
use Illuminate\Http\Request;

class DepreciationController extends Controller {
    public function index() {
        $this->need('finance.view');
        return view('depreciation.index', [
            'preview' => DepreciationService::preview(),
            'runs' => M\DepreciationRun::with('journal')->orderByDesc('period')->paginate(24),
            'defaultPeriod' => date('Y-m'),
        ]);
    }
    public function store(Request $r) {
        $this->need('finance.create');
        $run = DepreciationService::run($r->validate(['period' => ['required', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/']])['period']);
        return redirect()->route('depreciation-runs.show', $run->id)
            ->with('success', "Depreciation {$run->period} posted: ".cmoney($run->total_amount)." across {$run->assets_count} assets (JV {$run->journal->journal_no}).");
    }
    public function show(int $id) {
        $this->need('finance.view');
        $run = M\DepreciationRun::with('lines.asset', 'journal', 'runner')->findOrFail($id);
        return view('depreciation.show', ['run' => $run]);
    }
}
