<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Models\AuditLog;
use App\Models\Quote;
use App\Services\NotificationService;

final class ApprovalController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('approvals');
        view('approvals/index', [
            'title' => 'Approvals',
            'rows' => Quote::pendingApproval(),
            'notifications' => $this->notifications(),
        ]);
    }

    public function decide(Request $request): void
    {
        $this->requireModule('approvals');
        $this->verifyCsrf($request);
        $row = Quote::find((int) $request->param('id'));
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        if ($row['status'] !== 'pending_approval') {
            json_out(['ok' => false, 'error' => 'This quote is not waiting.'], 422);
        }
        $ok = (string) $request->input('decision') === 'approve';
        if ($ok) {
            Quote::update((int) $row['id'], [
                'status' => 'approved',
                'approved_at' => date('Y-m-d H:i:s'),
                'approved_by' => Auth::instance()->id(),
                'reject_reason' => null,
            ]);
            NotificationService::send((int) $row['owner_id'], 'Quote approved', (string) $row['title'], '/quotes/' . $row['id']);
            AuditLog::write('quote.approve', 'quote', (int) $row['id']);
            json_out(['ok' => true, 'message' => 'Approved. The salesperson can send it now.']);
        }
        $reason = trim((string) $request->input('reason', ''));
        if ($reason === '') {
            json_out(['ok' => false, 'error' => 'Enter a reason to reject.'], 422);
        }
        Quote::update((int) $row['id'], [
            'status' => 'rejected',
            'reject_reason' => $reason,
        ]);
        NotificationService::send((int) $row['owner_id'], 'Quote rejected', $reason, '/quotes/' . $row['id']);
        AuditLog::write('quote.reject', 'quote', (int) $row['id']);
        json_out(['ok' => true, 'message' => 'Rejected. The salesperson can fix and resubmit.']);
    }
}
