<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Session;
use App\Core\View;
use App\Repositories\ExecutiveActionRepository;
use App\Repositories\ExecutiveActionGovernanceRepository;
use App\Repositories\ExecutiveActionReviewRepository;
use App\Repositories\LeadershipHuddleRepository;
use Throwable;

final class ActionCenterController
{
    public function leadershipHuddle(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode, []);
        $huddle = [];
        $huddleError = null;

        try {
            $huddle = (new LeadershipHuddleRepository($hospitalCode))->report();
        } catch (Throwable $e) {
            $huddleError = $e->getMessage();
            $this->log($e);
        }

        View::render('leadership_huddle/index', [
            'title' => 'Leadership Huddle',
            'activePage' => 'leadership-huddle',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'huddle' => $huddle,
            'huddleError' => $huddleError,
        ]);
    }

    public function index(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode, []);
        $center = [];
        $centerError = null;

        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
        } catch (Throwable $e) {
            $centerError = $e->getMessage();
            $this->log($e);
        }

        View::render('action_center/index', [
            'title' => 'Executive Action Center',
            'activePage' => 'action-center',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'center' => $center,
            'centerError' => $centerError,
        ]);
    }



    public function reviewDashboard(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode, []);
        $days = (int)Request::get('days', '30');
        $days = max(7, min(90, $days));
        $includeQaRaw = strtolower(trim((string)Request::get('include_qa', '0')));
        $includeQaActivity = in_array($includeQaRaw, ['1', 'true', 'yes', 'on'], true);
        $center = [];
        $analytics = [];
        $centerError = null;

        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
            $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
            $operationalDate = (string)($op['operational_date'] ?? date('Y-m-d'));
            $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
            $analytics = (new ExecutiveActionReviewRepository($hospitalCode))->managementDashboard($actions, $operationalDate, $days, $includeQaActivity);
        } catch (Throwable $e) {
            $centerError = $e->getMessage();
            $this->log($e);
        }

        View::render('action_center/dashboard', [
            'title' => 'Executive Review Dashboard',
            'activePage' => 'action-center',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'center' => $center,
            'analytics' => $analytics,
            'days' => $days,
            'includeQaActivity' => $includeQaActivity,
            'centerError' => $centerError,
        ]);
    }


    public function governanceDashboard(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode, []);
        $center = [];
        $governance = [];
        $diagnostics = [];
        $centerError = null;

        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
            $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
            $operationalDate = (string)($op['operational_date'] ?? date('Y-m-d'));
            $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
            $repo = new ExecutiveActionGovernanceRepository($hospitalCode);
            $governance = $repo->managementSummary($actions, $operationalDate);
            $diagnostics = $repo->diagnostics($operationalDate);
        } catch (Throwable $e) {
            $centerError = $e->getMessage();
            $this->log($e);
        }

        View::render('action_center/governance', [
            'title' => 'Executive Governance Dashboard',
            'activePage' => 'action-center',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'center' => $center,
            'governance' => $governance,
            'governanceDiagnostics' => $diagnostics,
            'centerError' => $centerError,
        ]);
    }


    public function review(): void
    {
        Auth::requireLogin();

        $hospitalCode = Auth::hospital();
        $hospital = \config('hospitals.' . $hospitalCode, []);
        $ruleId = trim((string)Request::get('action', ''));
        $center = [];
        $centerError = null;
        $action = null;
        $auditHistory = [];
        $reviewDiagnostics = [];
        $previousReview = null;
        $allowedTransitions = ['open', 'reviewed', 'deferred'];
        $governance = [];
        $governanceHistory = [];
        $governanceDiagnostics = [];
        $operationalDate = date('Y-m-d');

        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
            $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
            $operationalDate = (string)($op['operational_date'] ?? $operationalDate);
            $actions = is_array($center['actions'] ?? null) ? $center['actions'] : [];
            foreach ($actions as $candidate) {
                if (is_array($candidate) && (string)($candidate['rule_id'] ?? '') === $ruleId) {
                    $action = $candidate;
                    break;
                }
            }
            $reviewRepo = new ExecutiveActionReviewRepository($hospitalCode);
            $reviewDiagnostics = $reviewRepo->diagnostics($operationalDate);
            if ($ruleId !== '') {
                if (!is_array($action)) {
                    $action = $reviewRepo->historicalAction($ruleId);
                }
                $auditHistory = $reviewRepo->auditHistoryAllDates($ruleId, 30);
                if (is_array($action) && empty($action['historical_only'])) {
                    $previousReview = is_array($action['previous_review'] ?? null)
                        ? $action['previous_review']
                        : $reviewRepo->latestReviewAcrossDates($ruleId, $operationalDate);
                }
                $currentReview = is_array($action['review'] ?? null) ? $action['review'] : [];
                $allowedTransitions = $reviewRepo->allowedTransitions((string)($currentReview['status'] ?? 'open'));

                $governanceRepo = new ExecutiveActionGovernanceRepository($hospitalCode);
                $governance = $governanceRepo->find($ruleId, $operationalDate);
                $governanceHistory = $governanceRepo->auditHistory($ruleId, 30);
                $governanceDiagnostics = $governanceRepo->diagnostics($operationalDate);
            }
        } catch (Throwable $e) {
            $centerError = $e->getMessage();
            $this->log($e);
        }

        View::render('action_center/review', [
            'title' => 'Action Review',
            'activePage' => 'action-center',
            'hospital' => $hospital,
            'hospitalCode' => $hospitalCode,
            'center' => $center,
            'centerError' => $centerError,
            'action' => $action,
            'ruleId' => $ruleId,
            'auditHistory' => $auditHistory,
            'reviewDiagnostics' => $reviewDiagnostics,
            'previousReview' => $previousReview,
            'allowedTransitions' => $allowedTransitions,
            'governance' => $governance,
            'governanceHistory' => $governanceHistory,
            'governanceDiagnostics' => $governanceDiagnostics,
            'operationalDate' => $operationalDate,
        ]);
    }

    public function updateGovernance(): void
    {
        Auth::requireLogin();

        $ruleId = trim((string)Request::post('action', ''));
        $token = (string)Request::post('_csrf', '');
        if (!Csrf::validate($token)) {
            Session::flash('governance_error', 'Invalid session token. Please try again.');
            \redirect('index.php?page=action-review&action=' . rawurlencode($ruleId) . '&lang=' . \current_lang());
        }

        $hospitalCode = Auth::hospital();
        $action = [];
        $operationalDate = date('Y-m-d');
        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
            $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
            $operationalDate = (string)($op['operational_date'] ?? $operationalDate);
            foreach ((array)($center['actions'] ?? []) as $candidate) {
                if (is_array($candidate) && (string)($candidate['rule_id'] ?? '') === $ruleId) {
                    $action = $candidate;
                    break;
                }
            }

            $input = [
                'owner_name' => (string)Request::post('owner_name', ''),
                'assigned_to' => (string)Request::post('assigned_to', ''),
                'due_date' => (string)Request::post('due_date', ''),
                'follow_up_date' => (string)Request::post('follow_up_date', ''),
                'escalation_level' => (string)Request::post('escalation_level', 'none'),
                'resolution_status' => (string)Request::post('resolution_status', 'active'),
                'resolution_note' => (string)Request::post('resolution_note', ''),
            ];
            (new ExecutiveActionGovernanceRepository($hospitalCode))->save($ruleId, $operationalDate, $input, Auth::name(), $action);
            Session::flash('governance_success', 'Governance ownership, follow-up and accountability were saved with audit evidence.');
        } catch (Throwable $e) {
            Session::flash('governance_error', $e->getMessage());
            $this->log($e);
        }

        \redirect('index.php?page=action-review&action=' . rawurlencode($ruleId) . '&lang=' . \current_lang());
    }

    public function updateReview(): void
    {
        Auth::requireLogin();

        $ruleId = trim((string)Request::post('action', ''));
        $status = trim((string)Request::post('status', 'open'));
        $note = trim((string)Request::post('note', ''));
        $token = (string)Request::post('_csrf', '');

        if (!Csrf::validate($token)) {
            Session::flash('review_error', 'Invalid session token. Please try again.');
            \redirect('index.php?page=action-review&action=' . rawurlencode($ruleId) . '&lang=' . \current_lang());
        }

        $hospitalCode = Auth::hospital();
        $center = [];
        $action = [];
        $operationalDate = date('Y-m-d');

        try {
            $center = (new ExecutiveActionRepository($hospitalCode))->center();
            $op = is_array($center['operational'] ?? null) ? $center['operational'] : [];
            $operationalDate = (string)($op['operational_date'] ?? $operationalDate);
            foreach ((array)($center['actions'] ?? []) as $candidate) {
                if (is_array($candidate) && (string)($candidate['rule_id'] ?? '') === $ruleId) {
                    $action = $candidate;
                    break;
                }
            }
            (new ExecutiveActionReviewRepository($hospitalCode))->save($ruleId, $operationalDate, $status, $note, Auth::name(), $action);
            Session::flash('review_success', 'Review status saved, management worklist updated, and Oracle audit trail recorded.');
        } catch (Throwable $e) {
            Session::flash('review_error', $e->getMessage());
            $this->log($e);
        }

        \redirect('index.php?page=action-review&action=' . rawurlencode($ruleId) . '&lang=' . \current_lang());
    }

    private function log(Throwable $e): void
    {
        $file = \storage_path('logs/app.log');
        $dir = dirname($file);
        if (!is_dir($dir)) { @mkdir($dir, 0775, true); }
        @file_put_contents($file, '[' . date('c') . '] ActionCenterController: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
    }
}
