<?php
namespace App\Http\Controllers;
use App\Models as M;
use App\Services\ApprovalService;
use Illuminate\Http\Request;
class ApprovalController extends Controller {
    public function index() {
        $this->need('dashboard.view');
        return view('approvals.index', [
            'pending' => M\Approval::with('requester')->where('status', 'pending')->orderByDesc('id')->paginate(20, ['*'], 'p'),
            'history' => M\Approval::with('requester', 'decider')->where('status', '!=', 'pending')->orderByDesc('id')->limit(30)->get(),
            'types' => ApprovalService::types()]);
    }
    public function decide(Request $r, int $id) {
        $a = M\Approval::findOrFail($id);
        abort_unless($a->status === 'pending', 403, 'Already decided.');
        $d = $r->validate(['decision' => 'required|in:approved,rejected', 'remarks' => 'nullable|max:500']);
        $this->need($this->permFor($a->document_type).'.approve');
        ApprovalService::decide($a, $d['decision'], $d['remarks'] ?? null);
        if ($r->wantsJson() || $r->expectsJson()) {
            return response()->json(['ok' => true, 'id' => $a->id, 'decision' => $d['decision'],
                'document' => $a->document_no, 'pending_left' => M\Approval::where('status', 'pending')->count()]);
        }
        return back()->with('success', 'Document '.$d['decision'].'.');
    }
    protected function permFor(string $type): string {
        return match ($type) {
            'purchase_requisition', 'purchase_order' => 'purchase',
            'leave_application', 'staff_advance' => 'hr',
            'expense_claim' => 'finance',
            'quotation' => 'sales',
            'subcontractor_claim', 'client_ipc' => 'projects',
            default => 'settings',
        };
    }
}
