<?php

function presSend($presType, $patientId, $doctorId, $presDate, $presContent, $for_husband) {

    $pres = R::xdispense('prescription');
    $pres->patient_id = $patientId;
    $pres->doctor_id = $doctorId;
    $pres->pres_date = $presDate;
    $pres->pres_type = $presType;
    $pres->user_id = $_SESSION['user_id'];
    $pres->create_date = date('Y-m-d H:i:s');


    switch ($presType) {
        case 1:
            $pres->pres_name = $presContent->name;
            $pres->pres_content = $presContent->content;
            $pres->for_husband = $for_husband;
            r::store($pres);
            break;

        default :
            $presId = r::store($pres);
            addDrugsContentPre($presContent, $presId);
            break;
    }

    return 1;
}

function addDrugsContentPre($pres, $presId) {
    foreach ($pres as $pre) {

        if ($pre['drugid'] > 0) {
            $dd = R::load('drugs', $pre['drugid']);
            $pres_details = R::xdispense('prescription_details');
            $pres_details->pres_id = $presId;
            $pres_details->drugname = $dd->drugname;
            $pres_details->drugtype = $pre['drugtype'];
            $pres_details->drugdos = $pre['drugdos'];
            r::store($pres_details);
        }
    }
}

function preDetails($presId) {
    $sql = 'select   prescription.id  , prescription.pres_date  , patients.statusno  , prescription.for_husband
                                , patients.wifename, patients.husdandname ,  awusers.name  as drName 
                                 , patients.husbandtypeid   , patients.wiftypeid   ,  prescription.pres_type
                                  ,  prescription.pres_name  ,  prescription.pres_content

                   from    prescription
                             join patients                             on patients.id  = prescription.patient_id
                               left join awusers                    on awusers.user_id = prescription.doctor_id  
                                
                         where    prescription.id  = ' . $presId;

    $pres = R::getRow($sql);

    $pres = patInfo($pres);
    if ($pres['pres_type'] != 1) {
        $pres['details'] = preInfo($pres['id']);
    }

    return $pres;
}

function preInfo($presId) {
    $details = R::findAll('prescription_details', ' pres_id = ? ', [$presId]);
    return $details;
}

function patInfo($pres) {
    if ($pres['for_husband'] == 1) {
        $husbandtypes = R::load('husbandtypes', $pres['husbandtypeid']);
        $pres['name'] = $pres['husdandname'];
        $pres['title'] = $husbandtypes->title;
    } else {
        $wifetypes = R::load('wifetypes', $pres['wiftypeid']);
        $pres['name'] = $pres['wifename'];
        $pres['title'] = $wifetypes->title;
    }
    return $pres;
}
