<?php 
if (!isset($_SESSION)){
  session_start();
}
include('accesscheck2.php');
require_once('Connections/courier.php');
include('functions/adjudication_rules.php'); 
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
mysql_select_db($database_courier, $courier);
$action=$_POST["act"];
$id = $_POST['id'];
$switch_id = $_POST["itemqty"];
$insurance_company_id = $_POST['insurer'];

$switchreason = $_POST['reason'];
$other = $_POST['other'];

if($reason=="other")
{$reason=$_POST['other'];
}

$mode_of_payment_all=$_POST['mode_of_payment_all'];
$provider_id=$_SESSION['provider_id']; 
$user_id=$_SESSION['myMM_Userid'];
$process_claim_no=$_POST['process_claim_no']; 
$attending_officer=$_POST['attending_officer'];
if($attending_officer=='Other'){
$attending_officer=$_POST['attending_officer_other'];	
}
 
$diagnosis=$_POST['diagnosis_diseases']; 
$type_of_visit=$_POST['patienttype'];
$date_of_consultation=$_POST['date_of_consultation'];

if($type_of_visit=="In-Patient"){
$date_of_admission=$date_of_consultation;	
}  

$provider_item_id=$_POST['provider_item_id']; 
$top_up = $_POST['top_up'];
$top_up_amount = $_POST['top_up_amount'];
$item_original_price = $_POST['item_original_price'];
$replacement_item_id = $_POST['replacement_item_id'];

if($action=='administrative_edit_claim_details_administrative'){
    //echo "asasa";exit();
  if($replacement_item_id > 0){
        $job_items = mysql_fetch_assoc(mysql_query("SELECT * FROM claims_details WHERE id='$replacement_item_id'"));
        $job_number = $job_items['job_number']; 
        mysql_query("UPDATE job_numbers SET audit_status='none' WHERE job_number='$job_number'");
  }else{ $job_number = null; }  
$queryItems = "SELECT * FROM service_items WHERE id='$id'";
$resultItems = mysql_query($queryItems) or die(mysql_error());
$arrayItems = mysql_fetch_assoc($resultItems);
$mode_of_payment_all=$_POST['mode_of_payment_all'];
$free_service = $arrayItems['free_service'];
$no_of_days = $arrayItems['no_of_days'];

$provider_item_id=$arrayItems['id'];
$ins_item_code=$arrayItems['ins_item_code'];
$provider_id_master=$arrayItems['provider_id_master'];
$item=$arrayItems['item'];
$rx_item_name=$arrayItems['rx_item_name'];
$rx_brand_name=$arrayItems['rx_brand_name'];
$rx_cartegory=$arrayItems['rx_cartegory'];
$rx_prescription_name=$arrayItems['rx_prescription_name'];
$item_cash_price = $arrayItems['price_'.$_SESSION['name_code']];
$item_class=$arrayItems['itemclass'];
$item_service=$arrayItems['service'];
$item_service_type=$arrayItems['service_type'];
$sub_item_service_type=$arrayItems['sub_service_type'];
$total_claim=1*$item_unit_price;
$total_award='';
if($item_service_type=='Optical Consultation'){
// if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'){
    $qty_available = 1;
}else{
    $qty_available = $arrayItems['quantity_available_'.$_SESSION['name_code']];
}

$queryItems = "SELECT * FROM claims_details WHERE process_claim_no='$process_claim_no' and provider_item_id='$provider_item_id'";
$resultItems = mysql_query($queryItems) or die(mysql_error());
$arrayItems = mysql_fetch_assoc($resultItems);
$totalRows = mysql_num_rows($resultItems);

$query_rsodest_claim_no = "select * from process_claim_no where process_claim_no='$process_claim_no'";
$rsodest_claim_no = mysql_query($query_rsodest_claim_no, $courier) or die(mysql_error());
$row_rsodest_claim_no = mysql_fetch_assoc($rsodest_claim_no);

$patient_no=$row_rsodest_claim_no['patient_no'];
$member_insurance_no=$row_rsodest_claim_no['insurance_no'];
$type_of_visit=$row_rsodest_claim_no['typeofvisit'];
$attending_officer=$row_rsodest_claim_no['attending_officer'];
$attending_officer_id=$row_rsodest_claim_no['attending_officer_id'];
$date_of_consultation=$row_rsodest_claim_no['date_added'];
$insurance_claim_no=$row_rsodest_claim_no['insurance_claim_no'];
$ins_company=$row_rsodest_claim_no['insurance_company'];
$api_ins_company=$row_rsodest_claim_no['insurance_company'];

if($qty_available < 1){
    $status = 'error';
    $message = strtoupper($item).' is Out of Stock.!';
} 

        ////////////////// Get previous visit history ///////////////////////////



$oldDate = mysql_fetch_assoc(mysql_query("SELECT date_added_short FROM claims_details WHERE process_claim_no <> '$process_claim_no' AND patient_no = '$patient_no' AND (payment_status = 'Paid' OR payment_status = 'Approved') AND mode_of_payment <> 'Review' AND provider_item_id = '$id' ORDER BY id DESC LIMIT 1"));

$newDate = mysql_fetch_assoc(mysql_query("SELECT date_added FROM process_claim_no WHERE process_claim_no ='$process_claim_no' AND patient_no = '$patient_no' ORDER BY id DESC LIMIT 1")); 
$start_date = strtotime($oldDate['date_added_short']); 
$end_date = strtotime($newDate['date_added']); 
$dateDiff = floor(abs(($end_date - $start_date)/60/60/24));

// echo $dateDiff;exit;


//     list($unit_price, $mode_of_payment_all, $payment_status, $selling_unit, $selling_qty) = get_price($provider_item_id, $ins_company, $mode_of_payment_all);	
// 	if ($free_service == "Yes" && $dateDiff <= $no_of_days) {
//     $payment_status = 'Paid';
//     $mode_of_payment_all = ucfirst('Review');
// }

list($unit_price, $mode_of_payment_all, $payment_status, $selling_unit, $selling_qty) = get_price($provider_item_id, $ins_company, $mode_of_payment_all);

//echo $unit_price;exit;
 //echo $item_service_type;exit;
if ($item_service_type=='Optical Consultation') {
 
    ///////////////////////////// Check if item exit on the promo table and if promo has not expired ///////////////////////////
    
    $promoResult = mysql_query("SELECT * FROM promotion_order a INNER JOIN promotion_order_details b ON b.promo_id = a.id WHERE item_id = '$id' AND CURRENT_DATE <= DATE_FORMAT(end_date, '%Y/%m/%d') AND branch = '".$_SESSION['branch_id']."'");
    $promoCount = mysql_num_rows($promoResult);
    if ($promoCount > 0) {
        $promoFetch = mysql_fetch_assoc($promoResult);
        $sysdate = $promoFetch['end_date'];
        $currentDate = date('Y-m-d');
        if ($currentDate <= $sysdate) {
         $payment_status = 'Paid';
         $mode_of_payment_all = ucfirst('Promo');
     }
    //  else{
    //     if ($free_service == "Yes" && $dateDiff <= $no_of_days) {
    //         $payment_status = 'Paid';
    //         $mode_of_payment_all = ucfirst('Review');
    //     }

    // }

}else{
 
    if ($free_service == "Yes" && $dateDiff <= $no_of_days) {
            $payment_status = 'Paid';
            $mode_of_payment_all = ucfirst('Review');
    }
    
}
}

// else {
//    if ($free_service == "Yes" && $dateDiff <= $no_of_days) {
//     $payment_status = 'Paid';
//     $mode_of_payment_all = ucfirst('Review');
// }

// }



        // $top_up_amount = $item_cash_price - $unit_price;
if ($top_up_amount > 0 && ($mode_of_payment_all == 'insurance'||$mode_of_payment_all == 'company') && $top_up != 'yes') {
    echo 'top_up@@@' . $top_up_amount;
    exit;
} else if ($top_up == 'yes' && ($unit_price - $top_up_amount) > 0) {
    $query_insert = "INSERT INTO `claims_details` (`id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`, `branch_id`,`sub_item_service_type`) VALUES (NULL, '$ins_company', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '$provider_item_id', '$ins_item_code', '$item (Cash Top Up)', '$item_class', '$item_service', '$item_service_type', '$top_up_amount', NOW(), CURDATE(), '1', '$top_up_amount', 'cash', '$patient_no', 'Owing', '$type_of_payment','".$_SESSION['branch_id']."','$sub_item_service_type');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    if($mode_of_payment_all == 'insurance'||$mode_of_payment_all == 'company'){
    //$unit_price = $item_original_price - $top_up_amount;
        $unit_price = $unit_price - $top_up_amount;
    }else{
    $unit_price = $unit_price - $top_up_amount;
    }
}else if($top_up == 'yes' && ($unit_price - $top_up_amount) == 0){
    $query_insert = "INSERT INTO `claims_details` (`id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`, `branch_id`,`sub_item_service_type`) VALUES (NULL, '$ins_company', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '$provider_item_id', '$ins_item_code', '$item', '$item_class', '$item_service', '$item_service_type', '$top_up_amount', NOW(), CURDATE(), '1', '$top_up_amount', 'cash', '$patient_no', 'Owing', '$type_of_payment','".$_SESSION['branch_id']."','$sub_item_service_type');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    if($mode_of_payment_all == 'insurance'||$mode_of_payment_all == 'company'){
    //$unit_price = $item_original_price - $top_up_amount;
        $unit_price = $unit_price - $top_up_amount;
    }else{
    $unit_price = $unit_price - $top_up_amount;
    }
}



if ($mode_of_payment_all != 'cash') {
    $member_no = $row_rsodest_claim_no['insurance_no'];
    $owing_status = 'Paid';
    $type_of_payment = 'Credit to ' . ucfirst($mode_of_payment_all);
} else {
    $owing_status = 'Owing';
}


$status = 'success';
$message = strtoupper($item).' has been added to the list Successfully !';

if($item_service_type=='Optical Lens' || $item=='Client Own Frame' || ($unit_price > 0 && $item_service_type != 'Optical Lens')){

    $query_insert = "INSERT INTO `claims_details` (`id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`, `branch_id`,`item_to_be_replaced`,`job_number`,`sub_item_service_type`) VALUES (NULL, '$ins_company', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '$provider_item_id', '$ins_item_code', '$item', '$item_class', '$item_service', '$item_service_type', '$unit_price', NOW(), CURDATE(), '1', '$unit_price', '$mode_of_payment_all', '$patient_no', '$payment_status', '$type_of_payment','".$_SESSION['branch_id']."','$replacement_item_id','$job_number','$sub_item_service_type');";
    $rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());
}


if($item_service_type=='Optical Consultation'){
// if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'){
$qty_available = 2;
}

if($rsinsert==TRUE){
    $qty_aval_text = 'quantity_available_'.$_SESSION['name_code'];
    $new_qty_avail = $qty_available-1;
    if($item_service_type=='Optical Consultation'){}else{
    // if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'){}else{
        mysql_query("UPDATE service_items SET $qty_aval_text='$new_qty_avail' WHERE id='$id'");
        }
}

if($insurance_claim_no!='' && $mode_of_payment_all!='cash'){
    if($type_of_visit=='Out Patient'){
    $type_of_visit_ins='Out-Patient';	
}

if($type_of_visit=='In Patient'){
$type_of_visit_ins='In-Patient';	
}

if ($top_up == 'yes' || $mode_of_payment_all == 'insurance'){
        $action_2 = 'addclaimitem';
        include('api_integration.php');
        if($status_code == '008'){

        }
    }
        }
    // }
    
echo $status.'@@@'.$message.'@@@';
include('view_items_claims_administrative.php'); 
}



if ($action == 'administrative_edit_claim_details_spectacle') {

    $queryItems = "SELECT * FROM service_items WHERE id='$id'";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);

    $provider_item_id = $arrayItems['id'];
    $ins_item_code = $arrayItems['ins_item_code'];
    $item = $arrayItems['item'];
    list($unit_price, $mode_of_payment_all, $payment_status, $selling_unit, $selling_qty) = get_price($provider_item_id, $ins_company, $mode_of_payment_all);
    $item_class = $arrayItems['itemclass'];
    $item_service = $arrayItems['service'];
    $item_service_type = $arrayItems['service_type'];

    $queryItems = "SELECT * FROM claims_details WHERE process_claim_no='$process_claim_no' and provider_item_id='$provider_item_id'";
    $resultItems = mysql_query($queryItems) or die(mysql_error());
    $arrayItems = mysql_fetch_assoc($resultItems);
    $totalRows = mysql_num_rows($resultItems);
    if ($totalRows > 0) {
        
    } else {
        $query_insert = "INSERT INTO `claims_details` (`id`, `mode_of_payment`, `ins_company`, `provider_id`, `member_no`, `patient_no`,`user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`,`payment_status`, `toothnos`, `insurance_claim_no`, `switched_from`) VALUES (NULL, '$mode_of_payment_all','$ins_company', '$provider_id', '$member_no', '$patient_no','$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '$provider_item_id', '$ins_item_code', '$item', '$item_class', '$item_service', '$item_service_type', '$unit_price', NOW(), CURDATE(), '1', '$unit_price', '$payment_status', '$toothnos', '$insurance_claim_no', '$switch_id')";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

        $switched_to_id = mysql_insert_id();



        if ($switch_id > 0) {
            $select_switched_claims = "select * from claims_details where id='$switch_id';";
            $rsselect_switched_claims = mysql_query($select_switched_claims, $courier) or die(mysql_error());
            $row_select_switched_claims = mysql_fetch_assoc($rsselect_switched_claims);
            $ins_company_switched = $row_select_switched_claims['ins_company'];
            $provider_item_id_switched = $row_select_switched_claims['provider_item_id'];
            $ins_item_code_switched = $row_select_switched_claims['ins_item_code'];
            $item_switched = $row_select_switched_claims['item'];
            $item_class_switched = $row_select_switched_claims['item_class'];
            $item_service_switched = $row_select_switched_claims['item_service'];
            $item_service_type_switched = $row_select_switched_claims['item_service_type'];
            $date_added_switched = $row_select_switched_claims['date_added'];
            $date_added_short_switched = $row_select_switched_claims['date_added_short'];
            $rx_item_name_switched = $row_select_switched_claims['rx_item_name'];
            $rx_cartegory_switched = $row_select_switched_claims['rx_cartegory'];
            $rx_prescription_name_switched = $row_select_switched_claims['rx_prescription_name'];
            $rx_brand_name_switched = $row_select_switched_claims['rx_brand_name'];
            $mode_of_payment_switched = $row_select_switched_claims['mode_of_payment'];
            $type_of_payment_switched = $row_select_switched_claims['type_of_payment'];
            $payment_status_switched = $row_select_switched_claims['payment_status'];
            $patient_no_switched = $row_select_switched_claims['patient_no'];
            $qty_switched = $row_select_switched_claims['qty'];
            $eye_optical_switched = $row_select_switched_claims['eye_optical'];
            $eye_spherical_switched = $row_select_switched_claims['eye_spherical'];
            $eye_cylindrical_switched = $row_select_switched_claims['eye_cylindrical'];
            $eye_add_switched = $row_select_switched_claims['eye_add'];
            $eye_pd_switched = $row_select_switched_claims['eye_pd'];
            $eye_axis_switched = $row_select_switched_claims['eye_axis'];
            $unit_price_switched = $row_select_switched_claims['unit_price'];
            $patient_no_switched = $row_select_switched_claims['patient_no'];




            $query_insert_switched = "INSERT INTO `claims_details_switched` (`switch_id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`,`qty`, `total_price`, `rx_item_name`, `rx_brand_name`, `rx_cartegory`, `rx_prescription_name`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`,`eye_optical`,`eye_spherical`,`eye_cylindrical`,`eye_add`,`eye_pd`, `eye_axis`) VALUES ($switch_id, '$ins_company_switched', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '$provider_item_id_switched', '$ins_item_code_switched', '$item_switched', '$item_class_switched', '$item_service_switched', '$item_service_type_switched', '$unit_price_switched', '$date_added_switched', '$date_added_short_switched', '$qty_switched', '$unit_price_switched','$rx_item_name_switched', '$rx_brand_name_switched', '$rx_cartegory_switched', '$rx_prescription_name_switched', '$mode_of_payment_switched', '$patient_no_switched', '$payment_status_switched', '$type_of_payment_switched', '$eye_optical_switched', '$eye_spherical_switched', '$eye_cylindrical_switched', '$eye_add_switched', '$eye_pd_switched', '$eye_axis_switched');";




            $rsinsert_switched = mysql_query($query_insert_switched, $courier) or die(mysql_error());


            $update_new_item_claims = mysql_query("update claims_details set eye_optical='$eye_optical_switched', eye_spherical='$eye_spherical_switched', eye_cylindrical='$eye_cylindrical_switched', eye_add='$eye_add_switched', eye_pd='$eye_pd_switched', eye_axis='$eye_axis_switched'  where id='$switched_to_id'")or die(mysql_error());

            $switch_insert = mysql_query("INSERT INTO switch (id,reason,switched_from,switched_to)VALUES('NULL','$switchreason','$switch_id','$switched_to_id')") or die(mysql_error());

            $select_switched_claims = mysql_query("DELETE from claims_details where id='$switch_id'")or die(mysql_error());
        }
    }
    include('view_items_claims_administrative.php');
}


if ($action == 'del_claim_details_administrative_administrative') {
    $resultItems2 = mysql_query("select * from claims_details where id='$id'") or die(mysql_error());
    $arrayItems2 = mysql_fetch_assoc($resultItems2);
    $item_id = $arrayItems2['provider_item_id'];
    $qty = $arrayItems2['qty'];
    $unit_price = $arrayItems2['unit_price'];
    $claim_no = $arrayItems2['process_claim_no'];
    $claim_item_name = explode('(CASH TOP UP)',strtoupper($arrayItems2['item']));
    if(count($claim_item_name)>1){
        $rsinsert = mysql_query("delete from claims_details where id='$id'", $courier) or die(mysql_error());
    }else{
    $arrayItems = mysql_fetch_assoc(mysql_query("SELECT * FROM service_items WHERE id='$item_id'"));
    $provider_item_id=$arrayItems['id'];
    $ins_item_code=$arrayItems['ins_item_code'];
    $item=$arrayItems['item'];
    if($arrayItems['service_type'] == 'Optical Accessories'){
        $item = 'Optical Accessories (CASE, LENS CLEANERS, CORD)';
    }
    else if($arrayItems['service_type'] == 'Optical Frame'){
        $item = 'Frame';
    }
    else if($arrayItems['service_type'] == 'Optical Contact Lens'){
        $item = 'Contact Lens';
    }

    $rsodest_claim_no = mysql_query("SELECT * from process_claim_no where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
    $row_rsodest_claim_no = mysql_fetch_assoc($rsodest_claim_no);
    $member_insurance_no=$row_rsodest_claim_no['insurance_no'];
    $attending_officer=$row_rsodest_claim_no['attending_officer'];
    $attending_officer_id=$row_rsodest_claim_no['attending_officer_id'];
    $date_of_consultation=$row_rsodest_claim_no['date_added'];
    $insurance_claim_no=$row_rsodest_claim_no['insurance_claim_no'];
    $ins_company=$row_rsodest_claim_no['insurance_company'];
    $api_ins_company=$row_rsodest_claim_no['insurance_company'];

    if($arrayItems2['mode_of_payment'] == 'insurance' && $insurance_claim_no != ''){
        if($qty == ''){ $qty = 0; }
        if($unit_price == ''){ $unit_price = 0; }
        $api_unit_price = $unit_price;
        $api_qty = $qty;
        $action_2 = 'deleteclaimitem';
        include('api_integration.php');
    }

// if(($status_code == '011' && $arrayItems2['mode_of_payment'] == 'insurance') || $arrayItems2['mode_of_payment'] != 'insurance'){
    $rsinsert = mysql_query("delete from claims_details where id='$id'", $courier) or die(mysql_error());
    if ($rsinsert == TRUE) {
        $qty_aval_text = 'quantity_available_'.$_SESSION['name_code'];
        $item_details = mysql_fetch_assoc(mysql_query("SELECT id, $qty_aval_text FROM service_items WHERE id='$item_id'"));
        $new_qty_avail = $item_details['quantity_available_'.$_SESSION['name_code']] + $arrayItems2['qty'];
        mysql_query("UPDATE service_items SET $qty_aval_text='$new_qty_avail' WHERE id='$item_id'");
    }
}
// }
    include('view_items_claims_administrative.php');
}


if ($action == 'del_invoice_details_administrative_administrative') {
    $query_insert = "delete from invoice_details where id='$id'";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    include('view_invoice_items_claims_administrative.php');
}


if($action=='administrative_edit_invoice_details_administrative'){
	$tdate=date('Y-m-d');
	//$patient_no = $_POST['patient_no'];
	
	$invoice_no=$_POST['invoice_no'];
$query_rsodest_claim = "select * from invoice_numbers where invoice_no='$invoice_no' and status='In Use'";
$rsodest_claim = mysql_query($query_rsodest_claim, $courier) or die(mysql_error());
	$row_rsodest_claim = mysql_fetch_assoc($rsodest_claim);
	//$invoice_no = $rsodest_claim['invoice_no'];
	  $query_rsodest_claim;
	

$queryItems = "SELECT * FROM service_items WHERE id='$id'";
$resultItems = mysql_query($queryItems) or die(mysql_error());
$arrayItems = mysql_fetch_assoc($resultItems);
$totalRows = mysql_num_rows($resultItems);

$mode_of_payment_all=$_POST['mode_of_payment_all'];

$provider_item_id=$arrayItems['id'];
$ins_item_code=$arrayItems['ins_item_code'];
$provider_id_master=$arrayItems['provider_id_master'];
$item=$arrayItems['item'];

if($mode_of_payment_all=='insurance'){$unit_price=$arrayItems["price_insurance"]; }
if($mode_of_payment_all=='company'){$unit_price=$arrayItems["price_company"];}
if($mode_of_payment_all=='cash'){$unit_price=$arrayItems["price_".$_SESSION['name_code']];}
if($mode_of_payment_all=='staff'){$unit_price=$arrayItems["price_staff"];}


$item_class=$arrayItems['itemclass'];
$item_service=$arrayItems['service'];
$item_service_type=$arrayItems['service_type'];
$total_claim=1*$item_unit_price;
$total_award='';

$queryItems = "SELECT * FROM invoice_details WHERE invoice_no='$invoice_no' and provider_item_id='$provider_item_id'";
$resultItems = mysql_query($queryItems) or die(mysql_error());
$arrayItems = mysql_fetch_assoc($resultItems);
$totalRows = mysql_num_rows($resultItems);
//echo $queryItems;

$query_rsodest_claim_no = "select * from invoice_numbers where invoice_no='$invoice_no'";
//echo $query_rsodest_claim;
$rsodest_claim_no = mysql_query($query_rsodest_claim_no, $courier) or die(mysql_error());
$row_rsodest_claim_no = mysql_fetch_assoc($rsodest_claim_no);
$totalRows_rsodest_claim_no = mysql_num_rows($rsodest_claim_no);

$patient_no=$row_rsodest_claim_no['patient_no'];
$type_of_visit=$row_rsodest_claim_no['typeofvisit'];
$attending_officer=$row_rsodest_claim_no['attending_officer'];
$date_of_consultation=$row_rsodest_claim_no['date_added'];

//$payment_mode=$row_rsodest_claim_no['mode_of_payment'];
if($mode_of_payment_all!='cash'){
$ins_company=$row_rsodest_claim_no['insurance_company'];	
$member_no=$row_rsodest_claim_no['insurance_no'];
$owing_status='Paid';
$type_of_payment='Credit to '.ucfirst($mode_of_payment_all);
}else{
$owing_status='Owing';	
}






if($totalRows>0){
/*$unit_qty=$arrayItems['item_qty']+1;
$total_claim=$item_qty*$item_unit_price;	
	
$query_insert="update claims_details set qty='$item_qty' where process_claim_no='$process_claim_no' and provider_item_id='$item_id'";	
$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());*/
	
}else{
	$query_insert = "INSERT INTO `invoice_details` (`id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `invoice_no`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`) VALUES (NULL, '$ins_company', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$invoice_no','$provider_item_id', '$ins_item_code', '$item', '$item_class', '$item_service', '$item_service_type', '$unit_price', NOW(), CURDATE(), '1', '$unit_price', '$mode_of_payment_all', '$patient_no', '$owing_status', '$type_of_payment');";	
	

	$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());
}


 include('view_invoice_items_claims_administrative.php'); 
	}


if($action=='del_claim_details_administrative_administrative1'){
$query_insert="delete from claims_details where id='$id'";	
$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());
	include('view_items_claims_administrative.php');


}

if($action=='updatesupply_claim_details_administrative'){
$dose = $_POST["itemqty"];
$query_insert="update claims_details set supplied='$dose' where id='$id'";
//echo $query_insert;
$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());

include('view_items_claims_administrative.php');

}

if($action=='updateprocure_administrative_claim_details_spectacle'){
$qty = $_POST["itemqty"];
$query_insert="update claims_details set procure_status='$qty' where id='$id'";
//echo $query_insert;
$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());

include('view_items_claims_administrative.php');

}

if ($action == 'update_claim_details_administrative') {
    $field = $_POST["field"];
    $value = $_POST["value"];
    $old_info = mysql_fetch_assoc(mysql_query("SELECT * FROM claims_details WHERE id = '$id'"));
    $qty = $old_info['qty'];
    $unit_price = $old_info['unit_price'];
    $item_id = $old_info['provider_item_id'];
    $mode_of_payment_all = $_POST['mode_of_payment_all'];

    $arrayItems = mysql_fetch_assoc(mysql_query("SELECT * FROM service_items WHERE id='$item_id'"));
    $provider_item_id=$arrayItems['id'];
    $ins_item_code=$arrayItems['ins_item_code'];
    $item=$arrayItems['item'];
    
    $qty_aval_text = 'quantity_available_'.$_SESSION['name_code'];
    $item_info = mysql_fetch_assoc(mysql_query("SELECT id,$qty_aval_text,service_type FROM service_items WHERE id='$item_id'"));
    $item_service_type = $item_info['service_type'];
    $qty_available = $item_info['quantity_available_'.$_SESSION['name_code']];

    if($item_service_type=='Optical Consultation'){
    // if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'){
        $qty_available = 1;
    }
    
    if ($field == 'qty') {
        if($qty_available<1){
          $status = 'error';
          $message = "Quantity is Out of Stock - " . strtoupper($item);  
        }
        else if ($value > $qty) {
            $status = 'success';
            $message = "Quantity has been Increased from $qty to $value - " . strtoupper($item);
            $update_type = 'Increase';
            $api_qty = $value;
        } else if ($value < $qty && $value > 0) {
            $status = 'success';
            $message = "Quantity has been Decreased from $qty to $value - " . strtoupper($item);
            $update_type = 'Decrease';
            $api_qty = $value;
        } else if ($value == 0) {
            $value = $qty;
            $status = 'error';
            $message = "Minimum Quantity can only be 1 (One) - " . strtoupper($item);
            $api_qty = $value;
        }

        if($api_qty == ''){
            $api_qty = $qty;
        }
        $api_unit_price = $unit_price;
        
        $qty_to_change = $value - $qty;
        if ($qty_to_change > 0) {
            $new_qty_avail = $qty_available - $qty_to_change;
        } else {
            $new_qty_avail = $qty_available + ($qty_to_change * -1);
        }
    } else if ($field == 'unit_price') {
        if ($value > $unit_price) {
            $status = 'success';
            $message = "Unit Price has been Increased from $unit_price to $value - " . strtoupper($item);
            $update_type = 'Increase';
            $api_unit_price = $value;
        } else if ($value < $unit_price) {
            $status = 'success';
            $message = "Unit Price has been Decreased from $unit_price to $value - " . strtoupper($item);
            $update_type = 'Decrease';
            $api_unit_price = $value;
        }
        if($api_unit_price == ''){
            $api_unit_price = $unit_price;
        }
        $api_qty = $qty;
    }

    if($item_service_type=='Optical Consultation'){
    // if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'){
        $new_qty_avail = 0;
    }

    $rsodest_claim_no = mysql_query("SELECT * from process_claim_no where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
    $row_rsodest_claim_no = mysql_fetch_assoc($rsodest_claim_no);
    $member_insurance_no=$row_rsodest_claim_no['insurance_no'];
    $attending_officer=$row_rsodest_claim_no['attending_officer'];
    $attending_officer_id=$row_rsodest_claim_no['attending_officer_id'];
    $date_of_consultation=$row_rsodest_claim_no['date_added'];
    $insurance_claim_no=$row_rsodest_claim_no['insurance_claim_no'];
    $ins_company=$row_rsodest_claim_no['insurance_company'];
    $api_ins_company=$row_rsodest_claim_no['insurance_company'];

    if($old_info['mode_of_payment'] == 'insurance' && $insurance_claim_no != ''){
        $action_2 = 'updateclaimitem';
        include('api_integration.php');
    }

    if(($status_code == '011' && $old_info['mode_of_payment'] == 'insurance') || $old_info['mode_of_payment'] != 'insurance'){
    if(($new_qty_avail >= 0 && $field == 'qty') || $field == 'unit_price' || $field == 'rx_prescription_name'){
    $rsinsert = mysql_query("update claims_details set $field = '$value' where id='$id'", $courier) or die(mysql_error());
    if ($rsinsert == TRUE) {
        $qty_aval_text = 'quantity_available_'.$_SESSION['name_code'];
        if($item_service_type=='Optical Consultation'|| $field == 'rx_prescription_name'){}else{
        // if($item_service_type=='Optical Lens' || $item_service_type=='Optical Consultation'|| $field == 'rx_prescription_name'){}else{
        mysql_query("UPDATE service_items SET $qty_aval_text='$new_qty_avail' WHERE id='$item_id'");
        }
    }
    }else{
        $status = 'error';
        $message = "Quantity Available is not enough for quantity entered - " . strtoupper($item); 
    }
}else{
    $status = 'error';
    $message = $status_message;
}
    
    echo $status.'@@@'.$message.'@@@';
    include('view_items_claims_administrative.php');
}


if($action=='updateprice_invoice_claim_details_administrative'){
	$get_quantity = mysql_query("SELECT qty FROM invoice_details where id='$id'");
	$rs_get_quantity = mysql_fetch_assoc($get_quantity);
	
	
$qtydrug = $_POST["itemqty"];
$total_price = $rs_get_quantity['qty'] * $qtydrug;

$query_insert="update invoice_details set unit_price='$qtydrug',total_price='$total_price' where id='$id'";	
$rsinsert=mysql_query($query_insert, $courier) or die(mysql_error());

$queryItems2 = "select * from invoice_details where id='$id'";
$resultItems2 = mysql_query($queryItems2) or die(mysql_error());
$arrayItems2 = mysql_fetch_assoc($resultItems2);

include('view_invoice_items_claims_administrative.php');
	
}

if ($action == 'forward_to_cashier_administrative' || $action == 'forward_to_cashier_administrative2') {
    $process_claim_no = $_POST['id'];
    $current_location = 'Cashier';
    $action_status = 'Sent to Cashier';
//  $query_insert = "update claims_details set current_location='$current_location', action_status='$action_status' where item_service='Administrative' AND process_claim_no='$process_claim_no'";
if ($action == 'forward_to_cashier_administrative') {
    mysql_query("update claims_details set current_location='$current_location', action_status='$action_status' where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
}else {
    mysql_query("update claims_details set current_location='$current_location', action_status='$action_status',comment='Credit Sales Payment' where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
}
    mysql_query("update process_claim_no set session_status='$current_location' where  process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
    $status = 'success';
    $message = "Success ! Client has been Forwarded to Cashier";
    echo $status . '@@@' . $message . '@@@';
    include('view_items_claims_administrative.php');
}

if($action == 'forward_balance_owing_cashier'){
    $process_claim_no = $_POST['id'];
    $user_id=$_SESSION['myMM_Userid'];

    $rsodest_claim_no = mysql_query("select * from process_claim_no where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
    $row_rsodest_claim_no = mysql_fetch_assoc($rsodest_claim_no);
    $patient_no=$row_rsodest_claim_no['patient_no'];
    $member_insurance_no=$row_rsodest_claim_no['insurance_no'];
    $type_of_visit=$row_rsodest_claim_no['typeofvisit'];
    $attending_officer=$row_rsodest_claim_no['attending_officer'];
    $attending_officer_id=$row_rsodest_claim_no['attending_officer_id'];
    $date_of_consultation=$row_rsodest_claim_no['date_added'];
    $insurance_claim_no=$row_rsodest_claim_no['insurance_claim_no'];
    $ins_company=$row_rsodest_claim_no['insurance_company'];
    $patient_no = $row_rsodest_claim_no['patient_no'];
    $patient_id = $row_rsodest_claim_no['patient_id'];

    $arrayItems = mysql_fetch_assoc(mysql_query("SELECT * FROM service_items LIMIT 1"));
    $provider_item_id=0;
    $provider_id = $arrayItems['provider_id'];
    $provider_id_master=$arrayItems['provider_id_master'];

    $patient_balance_info = mysql_fetch_assoc(mysql_query("SELECT patient_balance FROM patient_information WHERE id='$patient_id' AND patient_balance < 0;")); 
    $patient_balance = $patient_balance_info['patient_balance'] * -1;
    $total_owing = $patient_balance;

    $check_owing = mysql_num_rows(mysql_query("SELECT id FROM claims_details WHERE process_claim_no='$process_claim_no' AND item='BALANCE OWING'"));
    if($check_owing > 0){
    mysql_query("UPDATE claims_details SET unit_price='$total_owing',total_price='$total_owing',payment_status='Owing' WHERE process_claim_no='$process_claim_no' AND item='BALANCE OWING'");
    }else{
    $query_insert = "INSERT INTO `claims_details` (`id`, `ins_company`, `provider_id`, `provider_id_master`, `member_no`, `user_id`, `process_claim_no`,  `attending_officer`, `diagnosis`, `type_of_visit`, `date_of_consultation`, `date_of_admission`, `provider_item_id`, `ins_item_code`, `item`, `item_class`, `item_service`, `item_service_type`, `unit_price`, `date_added`, `date_added_short`, `qty`, `total_price`, `mode_of_payment`, `patient_no`, `payment_status`, `type_of_payment`, `branch_id`,`sub_item_service_type`) VALUES (NULL, '$ins_company', '$provider_id', '$provider_id_master', '$member_no', '$user_id', '$process_claim_no', '$attending_officer', '$diagnosis', '$type_of_visit', '$date_of_consultation', '$date_of_admission',  '', '', 'BALANCE OWING', '$item_class', '$item_service', '$item_service_type', '$total_owing', NOW(), CURDATE(), '1', '$total_owing', 'cash', '$patient_no', 'Owing', '$type_of_payment','".$_SESSION['branch_id']."','BALANCE OWING');";
    $rsinsert=mysql_query($query_insert) or die(mysql_error());
}

    mysql_query("update claims_details set current_location='Cashier', action_status='Sent to Cashier' where process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
    mysql_query("update process_claim_no set session_status='Cashier' where  process_claim_no='$process_claim_no'", $courier) or die(mysql_error());
}

if ($action == 'forward_to_claims_administrative') {
    $process_claim_no = $_POST['id'];
    $current_location = 'Claims Office';
    $action_status = 'Sent to Claims';
//  $query_insert = "update claims_details set current_location='$current_location', action_status='$action_status' where item_service='Administrative' AND process_claim_no='$process_claim_no'";
    $query_insert = "update claims_details set current_location='$current_location', action_status='$action_status' where process_claim_no='$process_claim_no'";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $query_insert = "update process_claim_no set session_status='$current_location' where  process_claim_no='$process_claim_no'";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());
    $status = 'success';
    $message = "Success ! Client has been Forwarded to Claims Office";

    echo $status . '@@@' . $message . '@@@';
    include('view_items_claims_administrative.php');
}

if ($action == 'forward_to_procurement') {
    $procurement_info = mysql_fetch_assoc(mysql_query("SELECT id FROM branches WHERE type='procurement' LIMIT 1"));
    list($process_claim_no, $job_number) = explode("[===]",$_POST['id']);
    $rsinsert = mysql_query("update job_numbers set audit_status = 'Job In-Transit', status_location_id='" . $procurement_info['id'] . "',front_desk_date=now() where process_claim_no='$process_claim_no' AND job_number='$job_number'", $courier);
    // $rsinsert = mysql_query("update process_claim_no set audit_status = 'Job In-Transit', status_location_id='" . $procurement_info['id'] . "',front_desk_date=now() where  process_claim_no='$process_claim_no'", $courier);
    mysql_query("INSERT INTO job_activities_status (process_claim_no,job_number,departure,arrival,departure_time,job_status,user_id,previous_id,status) VALUES('$process_claim_no','$job_number','" . $_SESSION['branch_id'] . "','" . $procurement_info['id'] . "',now(),'Job Sent','" . $user_id . "','0','closed')");
    mysql_query("INSERT INTO job_activities_status (process_claim_no,job_number,departure,arrival,departure_time,job_status,user_id,previous_id) VALUES('$process_claim_no','$job_number','" . $_SESSION['branch_id'] . "','" . $procurement_info['id'] . "',now(),'Job In-Transit','" . $user_id . "','".  mysql_insert_id()."')");

    $status = 'success';
    $message = "Success ! Client has been Forwarded to Main Procurement Successfully";

    echo $status . '@@@' . $message . '@@@';
    include('view_items_claims_administrative.php');
}

if ($action == 'reload_administrative_claim_administrative_administrative') {
    include('view_items_claims_administrative.php');
}

if($action=='delete_invoice'){
$query_delete="delete from invoice_details where invoice_no='$id'";	
$rsdelete=mysql_query($query_delete, $courier) or die(mysql_error());
include('view_patient.php');
}

if ($action == 'save_other_info' || $action == 'save_guest_status') {
    $id = $_POST['id'];
    $consulting_room_status = $_POST['consulting_room_status'];
    $next_location = $_POST['next_location'];
    $typeofvisit = $_POST['typeofvisit'];
    if ($consulting_room_status == 'pending') {
        mysql_query("UPDATE process_claim_no SET consulting_room_status='$consulting_room_status',typeofvisit='$typeofvisit',session_status='$next_location' WHERE process_claim_no ='$id'");
    } else {
        mysql_query("UPDATE process_claim_no SET consulting_room_status='$consulting_room_status',typeofvisit='$typeofvisit',session_status='$next_location',patient_status='Done' WHERE process_claim_no ='$id'");
    }
}


if($action == 'generate_job_number'){
list($process_claim_no,$patient_no) = explode("[===]",$_POST['id']);
$items_all = $_POST['item_trans_amount'];
    if (count($items_all) > 0) {
        $i=0;
    foreach ($items_all as $idd) {
        list($price, $id) = explode("[===]", $idd);
        $ids .= "id='$id' OR ";
        $check_status = mysql_num_rows(mysql_query("SELECT id FROM claims_details WHERE id='$id' AND item_service_type='Optical Lens' AND payment_status='Paid'"));
        if($check_status>0){
            $i++;
        }else{
            
        }
    }
    $ids = substr($ids, 0,-4);
}

if($i>0){
 $all_months = array('01'=> 1,'02'=>2,'03'=>3,'04'=>4,'05'=>5,'06'=>6,'07'=>7,'08'=>8,'09'=>9,'10'=>10,'11'=>11,'12'=>12);
 $month = date('m');
 $month2 = $all_months[$month];
 $job_no_max = mysql_fetch_assoc(mysql_query("SELECT MAX(job_number_int) AS max_job_number FROM job_numbers WHERE month_date='$month' AND branch_id='".$_SESSION['branch_id']."'")); 
 $max_job_no_int = $job_no_max['max_job_number'] + 1;
 $job_number = $_SESSION['branch_code'].$month2.'/'.$max_job_no_int;

 $check_count = mysql_num_rows(mysql_query("SELECT job_number FROM claims_details WHERE ($ids) AND job_number <> ''"));
 $check_count_approval = mysql_num_rows(mysql_query("SELECT id FROM claims_details WHERE ($ids) AND payment_status = 'Unapproved'"));
 if($check_count > 0){
    echo 'error@@@Job Number for Selected Items Already exist!@@@';
 } else if($check_count_approval > 0){
    echo 'error@@@Service Item(s) needs Approval to proceed!@@@';
 }else{
    mysql_query("INSERT INTO job_numbers(job_number_int,job_number,process_claim_no,patient_no,month_date,branch_id) VALUES('$max_job_no_int','$job_number','$process_claim_no','$patient_no','$month','".$_SESSION['branch_id']."')");
    mysql_query("UPDATE claims_details SET job_number='$job_number' WHERE ($ids)");
    echo 'success@@@Job Number Created Successfully!@@@';
 }
}else{
    echo 'error@@@Lens Must Be Fully Paid For.@@@';
}
 include('view_items_claims_administrative.php');
}