<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\IpdModel;
use App\Http\Controllers\MasterController;
use Session;

class IpdController extends Controller
{
    function addIpdCasePaper(Request $req){
        $id = $req->id ?? null;
        $ipdData = null;
        
        if ($id) {
            $ipdData = IpdModel::find($id);
            if (!$ipdData) {
                return redirect('ipdCasePaperList')->with('error', 'IPD case paper not found');
            }
        }
        
        return view('/ipd/add-ipd-casepaper', ['ipdData' => $ipdData, 'id' => $id]);
    }

    function generateIpdNo(){
        $maxIpdNo = IpdModel::max('IpdNo');
        $ipdNo = ($maxIpdNo) ? $maxIpdNo + 1 : 1;
        return response()->json(['ipd_no' => $ipdNo]);
    }

    function getPatientByMrdOrUhid(Request $req){
        $searchVal = $req->searchVal;
        
        $masterController = new MasterController();
        $patientRequest = new Request(['id' => $searchVal]);
        $patientDetailsJson = $masterController->getPatientDetails($patientRequest);
        $patientDetails = json_decode($patientDetailsJson, true);
        
        if($patientDetails){
            return response()->json($patientDetails);
        }
        
        return response()->json(['error' => 'Patient not found'], 404);
    }

    function saveIpdCasePaper(Request $req){
        try {
            if($req->actionvalue == 'Save'){
                $Ipd = new IpdModel;
            } else {
                $Ipd = IpdModel::find($req->saveid);
                if(!$Ipd){
                    return response()->json(['error' => 'IPD record not found'], 404);
                }
            }

            // Basic Patient Info
            $Ipd->IpdNo = $req->IpdNo;
            $Ipd->MrdNo = $req->MrdNo ? $req->MrdNo : null;
            $Ipd->UhidNo = $req->UhidNo ? $req->UhidNo : null;
            $Ipd->PatientName = $req->PatientName ? $req->PatientName : null;
            $Ipd->Age = $req->Age ? $req->Age : null;
            $Ipd->Gender = $req->Gender ? $req->Gender : null;
            $Ipd->Mobile = $req->Mobile1 ? $req->Mobile1 : ($req->Mobile ? $req->Mobile : null);
            $Ipd->Address = $req->Address ? $req->Address : null;
            $Ipd->Weight = $req->Weight ? $req->Weight : null;
            $Ipd->Temp = $req->Temp ? $req->Temp : null;
            $Ipd->Height = $req->Height ? $req->Height : null;
            
            // IPD Info
            $Ipd->AdmissionDate = ($req->AdmissionDate && $req->AdmissionDate != '') ? $req->AdmissionDate : null;
            $Ipd->AdmissionTime = $req->AdmissionTime ? $req->AdmissionTime : null;
            $Ipd->BloodGroup = $req->BloodGroup ? $req->BloodGroup : null;
            $Ipd->Type = $req->PatientType ? $req->PatientType : null;
            $Ipd->AadharCardNo = $req->AadharNo ? $req->AadharNo : null;
            // WardId is integer column, so only accept numeric values
            $WardId = null;
            if ($req->Ward && trim($req->Ward) != '') {
                // If Ward is numeric, convert to integer; otherwise set to null
                if (is_numeric($req->Ward)) {
                    $WardId = (int)$req->Ward;
                } else {
                    // If text value provided (like "Ward A"), set to null since WardId is integer
                    // You may need to add a WardName text column if you want to store ward names
                    $WardId = null;
                }
            }
            $Ipd->WardId = $WardId;
            $Ipd->BedNo = $req->BedNo ? $req->BedNo : null;
            
            // Weight/Height/Temp on Admission - store both values and dates
            $Ipd->WtOnAdm = $req->WtOnAdm ? $req->WtOnAdm : null;
            $Ipd->HtOnAdm = $req->HtOnAdm ? $req->HtOnAdm : null;
            $Ipd->TempOnAdm = $req->TempOnAdm ? $req->TempOnAdm : null;
            $Ipd->WtAdmissionDate = ($req->WtOnAdm && $req->WtOnAdm != '') ? date('Y-m-d') : null;
            $Ipd->HtAdmissionDate = ($req->HtOnAdm && $req->HtOnAdm != '') ? date('Y-m-d') : null;
            $Ipd->TmpAdmissionDate = ($req->TempOnAdm && $req->TempOnAdm != '') ? date('Y-m-d') : null;
            
            // Relative Details
            $Ipd->RelativeName = $req->RelativeName ? $req->RelativeName : null;
            $Ipd->RelativeName2 = $req->RelativeName2 ? $req->RelativeName2 : null;
            $Ipd->RelativeAddress = $req->RelativeAddress ? $req->RelativeAddress : null;
            $Ipd->Occupation = $req->Occupation ? $req->Occupation : null;
            $Ipd->RelativePhone = $req->Mobile1 ? $req->Mobile1 : null;
            $Ipd->RelativePhone2 = $req->Mobile2 ? $req->Mobile2 : null;
            $Ipd->RelativeOccupation = $req->Occupation ? $req->Occupation : null;
            
            // Diagnosis
            $Ipd->ProDiagnosis = $req->ProvisionalDiagnosis ? $req->ProvisionalDiagnosis : null;
            $Ipd->FinalDiagnosis = $req->FinalDiagnosis ? $req->FinalDiagnosis : null;
            $Ipd->DischargeStatus = $req->DischargeStatus ? $req->DischargeStatus : null;
            $Ipd->ReferedBy = $req->ReferredBy ? $req->ReferredBy : null;
            $Ipd->Consultant = $req->Consultant ? $req->Consultant : null;
            
            // Other Info
            $Ipd->AdmissionType = $req->AdmissionType ? $req->AdmissionType : null;
            $Ipd->AdmissionIndication = $req->Indication ? $req->Indication : null;
            $Ipd->AdmissionFor = $req->AdmissionFor ? $req->AdmissionFor : null;
            $Ipd->DeliveryPlace = $req->DeliveryPlace ? $req->DeliveryPlace : null;
            
            // System Fields
            $Ipd->Status = 1;
            $Ipd->CreatedBy = Session::get('UserId') ? Session::get('UserId') : 19;
            $Ipd->CreatedDate = date('Y-m-d');
            $Ipd->ModifiedBy = Session::get('UserId') ? Session::get('UserId') : 19;
            $Ipd->ModifiedDate = date('Y-m-d');
            
            $Ipd->save();
            
            return response()->json(['success' => true, 'id' => $Ipd->id, 'message' => 'IPD case paper saved successfully']);
            
        } catch (\Exception $e) {
            \Log::error('IPD save error: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to save IPD case paper: ' . $e->getMessage()], 500);
        }
    }

    function ipdCasePaperList(){
        $result = IpdModel::select('id', 'IpdNo', 'MrdNo', 'UhidNo', 'PatientName', 'Age', 'Gender', 
                    'Mobile', 'Address', 'AdmissionDate', 'AdmissionTime', 'WardId', 'BedNo', 
                    'Consultant', 'ProDiagnosis', 'FinalDiagnosis', 'ReferedBy', 'AdmissionType',
                    'CreatedDate', 'Status')
                ->where('Status', 1)
                ->orderBy('id', 'desc')
                ->get();
        
        // Map WardId to Ward Name for display
        $wardNames = [
            1 => 'Ward A',
            2 => 'Ward B',
            3 => 'Ward C',
            4 => 'Ward D',
            5 => 'ICU',
            6 => 'NICU',
            7 => 'PICU'
        ];
        
        // Add WardName to each result
        foreach ($result as $item) {
            if ($item->WardId && $item->WardId > 0 && isset($wardNames[$item->WardId])) {
                $item->WardName = $wardNames[$item->WardId];
            } else {
                $item->WardName = null;
            }
        }
        
        return view('/ipd/view-ipd-casepaper-list', ['data' => $result]);
    }

    function getIpdCasePaper(Request $req){
        try {
            $id = $req->id;
            $ipd = IpdModel::find($id);
            if (!$ipd) {
                return response()->json(['error' => 'IPD case paper not found'], 404);
            }
            return response()->json($ipd);
        } catch (\Exception $e) {
            \Log::error('Get IPD case paper error: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to fetch IPD case paper: ' . $e->getMessage()], 500);
        }
    }

    function deleteIpdCasePaper(Request $req){
        try {
            $id = $req->id;
            $ipd = IpdModel::find($id);
            if (!$ipd) {
                return response()->json(['success' => false, 'error' => 'IPD case paper not found'], 404);
            }
            $ipd->Status = 0;
            $ipd->ModifiedBy = Session::get('UserId') ?? 19;
            $ipd->ModifiedDate = date('Y-m-d');
            $ipd->save();
            return response()->json(['success' => true, 'message' => 'IPD case paper deleted successfully']);
        } catch (\Exception $e) {
            \Log::error('Delete IPD case paper error: ' . $e->getMessage());
            return response()->json(['success' => false, 'error' => 'Failed to delete IPD case paper: ' . $e->getMessage()], 500);
        }
    }
}
