<?php

namespace Modules\MedWorkforce\Http\Controllers;

use Illuminate\Http\Request;
use Modules\MedWorkforce\Entities\CredentialReview;
use Modules\MedWorkforce\Services\ComplianceService;

/**
 * Credential-compliance dashboard (SIFA P7-T1). Reads MedOrganization's
 * org_staff_licenses (via ComplianceService, fail-soft) alongside this module's
 * credential-review overlay, colour-coded by status with a status filter and an
 * "add review item" action. Viewing needs medwf.credentials.view; adding review
 * items needs medwf.credentials.manage.
 */
class ComplianceController extends MedWorkforceBaseController
{
    public function __construct(private ComplianceService $compliance)
    {
    }

    public function index(Request $request)
    {
        $this->guard('medwf.credentials.view');

        $dashboard = $this->compliance->buildDashboard($this->businessId());

        // Optional client-usable status filter (applied server-side for the table).
        $filter = $request->get('status');
        $staff = $dashboard['staff'];
        if ($filter && in_array($filter, [
            ComplianceService::STATUS_VALID,
            ComplianceService::STATUS_EXPIRING,
            ComplianceService::STATUS_EXPIRED,
            ComplianceService::STATUS_MISSING,
        ], true)) {
            $staff = array_values(array_filter($staff, fn ($s) => $s['license_status'] === $filter));
        }

        return view('medworkforce::compliance.index', [
            'staff'        => $staff,
            'counts'       => $dashboard['counts'],
            'hasOrg'       => $dashboard['has_org'],
            'expiringDays' => $dashboard['expiring_days'],
            'filter'       => $filter,
            'canManage'    => auth()->user()->can('medwf.credentials.manage'),
        ]);
    }

    /** "Add review item" modal form. */
    public function reviewForm(Request $request)
    {
        $this->guard('medwf.credentials.manage');

        return view('medworkforce::compliance.review_form', [
            'staff'     => $this->staff(),
            'userId'    => $request->filled('user_id') ? (int) $request->get('user_id') : null,
            'itemTypes' => CredentialReview::ITEM_TYPES,
            'statuses'  => CredentialReview::STATUSES,
        ]);
    }

    /** Persist a credential review item. */
    public function reviewStore(Request $request)
    {
        $this->guard('medwf.credentials.manage');

        $data = $this->validate($request, [
            'user_id'        => 'required|integer',
            'item_type'      => 'required|in:' . implode(',', CredentialReview::ITEM_TYPES),
            'title'          => 'required|string|max:191',
            'due_date'       => 'nullable|date',
            'completed_date' => 'nullable|date',
            'status'         => 'required|in:' . implode(',', CredentialReview::STATUSES),
            'notes'          => 'nullable|string|max:500',
        ]);

        try {
            CredentialReview::create([
                'business_id'    => $this->businessId(),
                'user_id'        => (int) $data['user_id'],
                'item_type'      => $data['item_type'],
                'title'          => $data['title'],
                'due_date'       => $data['due_date'] ?? null,
                'completed_date' => $data['completed_date'] ?? null,
                'status'         => $data['status'],
                'notes'          => $data['notes'] ?? null,
            ]);

            return $this->ok(__('medworkforce::lang.review_saved'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** Delete a review item. */
    public function reviewDestroy($id)
    {
        $this->guard('medwf.credentials.manage');

        try {
            $review = CredentialReview::forBusiness($this->businessId())->findOrFail($id);
            $review->delete();

            return $this->ok(__('medworkforce::lang.review_deleted'));
        } catch (\Exception $e) {
            return $this->fail();
        }
    }
}
