<?php

namespace App\Controllers;

use App\Traits\ResponseTrait;
use CodeIgniter\Controller;
use App\Models\PatResultModel;
use App\Models\OrderTest\OrderTestModel;
use App\Models\Patient\PatientModel;

class ReportController extends Controller {
    use ResponseTrait;

    protected $resultModel;
    protected $orderModel;
    protected $patientModel;

    public function __construct() {
        $this->resultModel = new PatResultModel();
        $this->orderModel = new OrderTestModel();
        $this->patientModel = new PatientModel();
    }

    /**
     * Generate HTML lab report for an order
     * GET /api/report/{orderID}
     */
    public function view($orderID) {
        try {
            // Get order details
            $order = $this->orderModel->find((int)$orderID);
            
            if (!$order) {
                return $this->respond([
                    'status' => 'failed',
                    'message' => 'Order not found',
                    'data' => []
                ], 404);
            }

            // Get patient details
            $patient = $this->patientModel->find($order['InternalPID']);
            
            if (!$patient) {
                return $this->respond([
                    'status' => 'failed',
                    'message' => 'Patient not found',
                    'data' => []
                ], 404);
            }

            // Get results for this order
            $results = $this->resultModel->getByOrder((int)$orderID);

            // Prepare data for the view
            $data = [
                'patient' => $patient,
                'order' => $order,
                'results' => $results,
                'generatedAt' => date('Y-m-d H:i:s')
            ];

            // Return HTML view
            return view('reports/lab_report', $data);

        } catch (\Exception $e) {
            log_message('error', 'ReportController::view error: ' . $e->getMessage());
            return $this->respond([
                'status' => 'failed',
                'message' => 'Failed to generate report',
                'data' => []
            ], 500);
        }
    }
}
