<?php session_start();
include('accesscheck2.php');
require_once('Connections/courier.php'); 
require_once('functions/functions.php'); 

$id = $_POST['id'];
if ($action == 'approve_gratis') {
    $qry = mysql_query("UPDATE claims_details SET payment_status = 'Approved',approved_by='".$_SESSION['myMM_Userid']."' WHERE id = '$id';");
    if ($qry == TRUE) {
        echo 'success@@@Gratis Approved Successfully!';
    }
} 

if ($action == 'approve_credit_sales') {
    $due_date = $_POST['due_date_'.$id];
    $qry = mysql_query("UPDATE claims_details SET payment_status = 'Approved',approved_by='".$_SESSION['myMM_Userid']."',payment_due_date='$due_date' WHERE id = '$id';");
    if ($qry == TRUE) {
        echo 'success@@@Credit Sales Approved Successfully!';
    }
} 

if ($action == 'forward_discount') {
    $patient_details = mysql_fetch_assoc(mysql_query("SELECT patient_id,patient_no FROM process_claim_no WHERE process_claim_no = '$id'"));
    $patient_id = $patient_details['patient_id'];
    $patient_no = $patient_details['patient_no'];
    $status = 'Unapproved';

    $discount_type = $_POST['discount_type'];
    $discount_rate = ($_POST['discount_rate'] / 100);
    $amount = $_POST['amount'];
    $discount_reason = $_POST['discount_reason'];
    $item_trans_id = $_POST['item_trans_id'];
    $item_trans_amount = $_POST['item_trans_amount'];
    $value = $_POST['value'];

    if(count($item_trans_amount) > 0){
    foreach ($item_trans_amount as $trans_amountt) {
        list($trans_amount, $ooo) = explode("[===]",$trans_amountt);
        $total_amount = $total_amount + (float) $trans_amount;
    }

    if ($value == 'apply') {
        $status = 'Approved';
    }

    if ($discount_type == 'fixed') {
        $discount = number_format($amount, 2);
        $discount_rate = ($amount / $total_amount) * 100;
    } else if ($discount_type == 'rate') {
        $discount = number_format($discount_rate * $total_amount, 2);
    }

    foreach ($item_trans_amount as $trans_amountt) {
        list($trans_amount, $itemtransid) = explode("[===]",$trans_amountt);
        $check_if_applied = mysql_query("SELECT id,item FROM claims_details where discount_applied='applied' and id='$itemtransid';");
        $check_if_applied_count = mysql_num_rows($check_if_applied);
        $check_if_applied_row = mysql_fetch_assoc($check_if_applied);
        if($check_if_applied_count > 0){
            echo "error@@@Sorry, Discount has already been Applied to ".$check_if_applied_row['item']."!. Uncheck it and Try again";
            exit;
        }
    }

    $insert = mysql_query("INSERT INTO patient_visit_discounts(patient_id,patient_no,process_claim_no,discount_type,discount_rate,discount_reason,total_amount,discount_amount,discount_status,user_id,branch_id) VALUES('$patient_id','$patient_no','$id','$discount_type','$discount_rate','$discount_reason','$total_amount','$discount','$status','" . $_SESSION['myMM_Userid'] . "','" . $_SESSION['branch_id'] . "')");
    $new_id = mysql_insert_id();

    foreach ($item_trans_amount as $trans_amountt) {
        list($trans_amount, $itemtransid) = explode("[===]",$trans_amountt);
        $query_insert = "update claims_details set discount_applied='applied',discount_id='$new_id' where id='$itemtransid';";
        $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error($courier));
    }

    if ($insert == TRUE) {
        if ($status == 'Approved') {
            echo "success@@@A Discount of GHS $discount has been Applied Successfully to this Client!";
        } else {
            echo "success@@@Discount of GHS $discount has been sent Successfully for Approval!";
        }
    }
}else{
    echo "error@@@Please Select the Items on which discount will be applied!";
}
}

if ($action == 'approve_discount') {
    $value = $_POST['value'];
    if ($value == 'Remove') {
        $qry = mysql_query("DELETE FROM patient_visit_discounts WHERE id='$id'");
        echo 'success@@@Discount has been Removed Successfully!';
    } else {
        $qry = mysql_query("UPDATE patient_visit_discounts SET discount_status = '$value" . "d',approved_by='" . $_SESSION['myMM_Userid'] . "' WHERE id = '$id';");
        echo "success@@@Discount has been $value" . "d Successfully!";
    }
}

if($action=="view_patient_cash_payments")
{
$get_payment_details = mysql_query("SELECT * FROM claims_details where receipt_number='$id'")or die(mysql_error());
$rs_get_details = mysql_fetch_assoc($get_payment_details);
$totaldetails = mysql_num_rows($get_payment_details);?>
		
                                <table class="table table-striped table-bordered">
                                <thead>
										    <tr>
										      <th class="count">&nbsp;</th>
										      <th>Item</th>
										      <th>Amount</th>
										      <th>Status</th>
										    </tr>
									      </thead>
                                          <tbody>
                                          <?php 
                                          if ($totaldetails> 0) { 
                                                    do {$start_row=$start_row+1;?>
										<tr>
										      <td height="23" valign="top" class="count"><span><?php echo $start_row; ?></span></td>
										      <td valign="top" style="cursor: pointer;"><?php echo $rs_get_details['item']; ?></td>
                                                                                      <td valign="top" style="cursor: pointer;"><?php echo number_format($rs_get_details['total_price'],2); ?></td>
										      <td valign="top" style="cursor: pointer;color: green;font-weight: bold;"><?php echo $rs_get_details['payment_status']; ?></td>
									        </tr>
							<?php } while ($rs_get_details = mysql_fetch_assoc($get_payment_details)); ?>
					    <?php } else { ?>
                                            <tr>
                                                <td style="color:red;" height="23" colspan="10" valign="top" class="count">Sorry, No Payment Records found</td>
									        </tr>
                                            
                                            <?php }?>
                                          </tbody>
                                </table>
                               

<?php	
	
}

if ($action == 'fetch_receiptnos') {
    $process_claim_no = mysql_real_escape_string($_POST['id']);
    $all_activiities = mysql_query("SELECT * FROM cashier_payments WHERE process_claim_no = '$process_claim_no' ORDER BY id ASC;");?>
<form name="form_receipt" id="form_receipt" class="form-horizontal">
        <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th style="text-align: center;">
                    <label class="mt-checkbox mt-checkbox-outline" ><input id="parent_box" type="checkbox" onchange="checkBoxes();"><span></span></label>
                </th>
                <th>Date Time</th>
                <th>Receipt No.</th>
                <th style="text-align: right;">Total Amount</th>
                <th>Received By</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $i=1;
            while ($row = mysql_fetch_assoc($all_activiities)) { ?>
                <tr>
                    <td style="text-align: center;"> <label class="mt-checkbox mt-checkbox-outline"><input value="<?php echo $row['receiptno'];?>" name="print_options[]" multiple="" class="item_check_box" type="checkbox"><span></span></label></td>
                    <td><?php echo date('jS F, Y g:i a',strtotime($row['date_added'])); ?></td>
                    <td><?php echo $row['receiptno']; ?></td>
                    <td style="text-align: right;"><?php echo 'GHC '. number_format($row['amount'],2); ?></td>
                    <td><?php echo $row['cashier_name'];?></td>
                    <td>
                         <label onclick="getcashierprint('<?php echo $process_claim_no; ?>','<?php echo $row['receiptno']; ?>','<?php echo $row['type_of_patient']; ?>');" id="hide_discount_btn" class="btn red btn-outline btn-circle btn-sm active" data-toggle="modal" href="#large">
                                          Print Receipt <i class="fa fa-print"></i>
                         </label>
                    </td>
                </tr>
            <?php $i++; } ?>
        </tbody>
    </table>
</form>
                
                
                <?php
}

if ($action == 'approve_item_cancellation') {
    $value = $_POST['value'];
    if ($value == 'Remove') {
        $qry = mysql_query("DELETE FROM items_cancel_swap WHERE id='$id'");
        echo 'success@@@Item has been Removed Successfully!';
    } else if ($value == 'Approved and Refund' || $value == 'Approved') {
        $row = mysql_fetch_assoc(mysql_query("SELECT * FROM items_cancel_swap WHERE id='$id'"));
        $row_claims = mysql_fetch_assoc(mysql_query("SELECT id,payment_status,discount_id,patient_no FROM claims_details WHERE id='".$row['claim_id']."'"));
        mysql_query("UPDATE items_cancel_swap SET status='Approved and Refund',approved_by='" . $_SESSION['myMM_Fullname'] . "' WHERE id='$id'");
        mysql_query("INSERT INTO refund_payments (patient_no,process_claim_no,item,claim_id,qty,unit_price,initiated_by,branch_id,reason) VALUES('" . $row['patient_no'] . "','" . $row['process_claim_no'] . "','" . $row['item'] . "','" . $row['claim_id'] . "','" . $row['qty'] . "','" . $row['unit_price'] . "','" . $_SESSION['myMM_Fullname'] . "','" . $_SESSION['branch_id'] . "','".$row['reason']."')");
        $payment_status = $row_claims['payment_status'].'-Cancelled';
        mysql_query("UPDATE claims_details SET payment_status='$payment_status' WHERE id='".$row['claim_id']."'");
        echo "success@@@Item has been $value" . "d Successfully!";
    } else {
        $row = mysql_fetch_assoc(mysql_query("SELECT * FROM items_cancel_swap WHERE id='$id'"));
        $row_claims = mysql_fetch_assoc(mysql_query("SELECT payment_status FROM claims_details WHERE id='".$row['claim_id']."'"));
        $payment_status = $row_claims['payment_status'].'-Cancelled';
        mysql_query("UPDATE claims_details SET payment_status='$payment_status' WHERE id='".$row['claim_id']."'");
        $qry = mysql_query("UPDATE items_cancel_swap SET status = '$value',approved_by='" . $_SESSION['myMM_Fullname'] . "' WHERE id = '$id';");
        echo "success@@@Item has been $value" . "d Successfully!";
    }

    if($value == 'Approved and Refund' || $value == 'Approved'){
    $id = $row['claim_id'];
    $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'];

    $insert_cancelled = mysql_query("INSERT INTO claims_details_cancelled SELECT * FROM claims_details WHERE id='$id';");
    if($insert_cancelled){
        mysql_query("DELETE FROM claims_details WHERE id='$id';");
    }
    $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');
    }

        $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'");
}
}

if ($action == 'approve_refund') {
    $value = $_POST['value'];
    if ($value == 'Remove') {
        $qry = mysql_query("DELETE FROM refund_payments WHERE id='$id'");
        echo 'success@@@Refund has been Removed/Deleted Successfully!';
    } else {
        $row = mysql_fetch_assoc(mysql_query("SELECT claim_id FROM refund_payments WHERE id='$id'"));
        $row_claims = mysql_fetch_assoc(mysql_query("SELECT id,payment_status,discount_id,patient_no,qty,unit_price FROM claims_details_cancelled WHERE id='" . $row['claim_id'] . "'"));
        $payment_status = $row_claims['payment_status'] . '-Refunded';
        mysql_query("UPDATE claims_details_cancelled SET payment_status='$payment_status' WHERE id='" . $row['claim_id'] . "'");
        $qry = mysql_query("UPDATE refund_payments SET status = '$value',approved_by='" . $_SESSION['myMM_Fullname'] . "' WHERE id = '$id';");

        $total_refunded = $row_claims['qty']*$row_claims['unit_price'];
        $total_discount = getItemDiscoutAmount($row_claims['id'], $row_claims['discount_id']);
        $overall_total_refunded = $total_refunded-$total_discount;
        mysql_query("UPDATE patient_information SET patient_balance=patient_balance+($overall_total_refunded) WHERE card_number='".$row_claims['patient_no']."'");
        echo "success@@@Refund has been $value" . " Successfully!";
    }
}

if($action== 'add_new_lens_price'){  ?>
<div class="modal-body"> 
    <div class="portlet light bordered">
                                        <!-- <div class="portlet-title">Add New Lens Price</div> -->
                                <div class="portlet-body form">
                    <form role="form" action="#" id="save_new_lens_price" class="form-horizontal">
                        <div class="form-body">
                            <div class="row" id="investment_plan_wrapper">    
                                <div class="col-lg-12 col-xs-12 col-md-12">

                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Addition</span></label>
                                        <div class="col-md-7">
                                            <input name="addition_name" id="addition_name" type="text" class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Material</span></label>
                                        <div class="col-md-7">
                                            <select name="material_name" id="material_name" class="form-control">
                                                <option value="PLASTIC">PLASTIC</option>
                                                <option value="GLASS">GLASS</option>
                                                <option value="POLYCARBONATE">POLYCARBONATE</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Lens Type</span></label>
                                        <div class="col-md-7">
                                            <select name="lens_type_name" id="lens_type_name" class="form-control">
                                                <option value="SINGLE VISION">SINGLE VISION</option>
                                                <option value="BIFOCAL">BIFOCAL</option>
                                                <option value="PROGRESSIVE">PROGRESSIVE</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Spherical Values</span></label>
                                        <div class="col-md-7">
                                            <div class="row">
                                            <div class="col-md-6">
                                                <input placeholder="Lower Value" name="spherical_lower" id="spherical_lower" type="text" class="form-control">
                                            </div>
                                            <div class="col-md-6">
                                                <input placeholder="Upper Value" name="spherical_upper" id="spherical_upper" type="text" class="form-control">
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Cylindrical Values</span></label>
                                        <div class="col-md-7">
                                            <div class="row">
                                            <div class="col-md-6">
                                                <input placeholder="Lower Value" name="cylindrical_lower" id="cylindrical_lower" type="text" class="form-control">
                                            </div>
                                            <div class="col-md-6">
                                                <input placeholder="Upper Value" name="cylindrical_upper" id="cylindrical_upper" type="text" class="form-control">
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Lens Price</span></label>
                                        <div class="col-md-7">
                                            <input name="lens_price" id="lens_price" type="text" class="form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions right">
                            <a data-dismiss="modal" class="btn red close_page_refresh"> Close </a>
                            <a class="btn green" onclick="saveInformation2('save_new_lens_price','','form#save_new_lens_price','');return false;"> Save Lens Price <i class="fa fa-check"></i> </a>
                        </div>
                    </form>
                </div>

                                </div>
                        </div>

<?php
}

if($action == 'save_new_lens_price'){
    $addition_name = strtoupper($_POST['addition_name']);
    $material_name = $_POST['material_name'];
    $lens_type_name = $_POST['lens_type_name'];
    $spherical_lower = $_POST['spherical_lower'];
    $spherical_upper = $_POST['spherical_upper'];
    $cylindrical_lower = $_POST['cylindrical_lower'];
    $cylindrical_upper = $_POST['cylindrical_upper'];
    $lens_price = $_POST['lens_price'];

    $insert = mysql_query("INSERT INTO lens_price(additions,material,lens_type,spherical_lower,spherical_upper,cylindrical_lower,cylindrical_upper,lens_price) VALUES('$addition_name','$material_name','$lens_type_name','$spherical_lower','$spherical_upper','$cylindrical_lower','$cylindrical_upper','$lens_price')");
    if($insert == TRUE){
    mysql_query("INSERT INTO lens_types SET parent_name='ADDITIONS' AND lens_name='$addition_name'");
    echo 'Lens Price Added successfully!@@@success';
    }else{
        echo 'The Lens Price might already exist!@@@error';
    }

}

if($action == 'edit_lens_price'){
$id = $_POST['id']; 
$row = mysql_fetch_assoc(mysql_query("SELECT * FROM lens_price WHERE id='$id'"))
?>
<div class="modal-body"> 
    <div class="portlet light bordered">
                                        <!-- <div class="portlet-"> <center><b>Update Lens Price</b></center></div> -->
                                <div class="portlet-body form">
                    <form role="form" action="#" id="save_new_lens_price" class="form-horizontal">
                        <div class="form-body">
                            <div class="row" id="investment_plan_wrapper">    
                                <div class="col-lg-12 col-xs-12 col-md-12">
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Addition</span></label>
                                        <div class="col-md-7">
                                            <input value="<?php echo $row['additions']; ?>" name="addition_name" id="addition_name" type="text" class="form-control">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Material</span></label>
                                        <div class="col-md-7">
                                            <select name="material_name" id="material_name" class="form-control">
                                                <option <?php if($row['material'] == 'PLASTIC'){ echo 'selected=""';} ?> value="PLASTIC">PLASTIC</option>
                                                <option <?php if($row['material'] == 'GLASS'){ echo 'selected=""';} ?> value="GLASS">GLASS</option>
                                                <option <?php if($row['material'] == 'POLYCARBONATE'){ echo 'selected=""';} ?> value="POLYCARBONATE">POLYCARBONATE</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Lens Type</span></label>
                                        <div class="col-md-7">
                                            <select name="lens_type_name" id="lens_type_name" class="form-control">
                                                <option <?php if($row['lens_type'] == 'SINGLE VISION'){ echo 'selected=""';} ?> value="SINGLE VISION">SINGLE VISION</option>
                                                <option <?php if($row['lens_type'] == 'BIFOCAL'){ echo 'selected=""';} ?> value="BIFOCAL">BIFOCAL</option>
                                                <option <?php if($row['lens_type'] == 'PROGRESSIVE'){ echo 'selected=""';} ?> value="PROGRESSIVE">PROGRESSIVE</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Spherical Values</span></label>
                                        <div class="col-md-7">
                                            <div class="row">
                                            <div class="col-md-6">
                                                <input placeholder="Lower Value" name="spherical_lower" id="spherical_lower" type="text" class="form-control" value="<?php echo $row['spherical_lower'];?>">
                                            </div>
                                            <div class="col-md-6">
                                                <input placeholder="Upper Value" name="spherical_upper" id="spherical_upper" type="text" class="form-control" value="<?php echo $row['spherical_upper'];?>">
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Cylindrical Values</span></label>
                                        <div class="col-md-7">
                                            <div class="row">
                                            <div class="col-md-6">
                                                <input placeholder="Lower Value" name="cylindrical_lower" id="cylindrical_lower" type="text" class="form-control" value="<?php echo $row['cylindrical_lower'];?>">
                                            </div>
                                            <div class="col-md-6">
                                                <input placeholder="Upper Value" name="cylindrical_upper" id="cylindrical_upper" type="text" class="form-control" value="<?php echo $row['cylindrical_upper'];?>">
                                            </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"><span class="pull-left">Lens Price</span></label>
                                        <div class="col-md-7">
                                            <input name="lens_price" id="lens_price" type="text" class="form-control" value="<?php echo $row['lens_price'];?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-actions right">
                            <a data-dismiss="modal" class="btn red close_page_refresh"> Close </a>
                            <a class="btn green" onclick="saveInformation2('update_lens_price','<?php echo $id; ?>','form#save_new_lens_price','');return false;"> Update Lens Price <i class="fa fa-check"></i> </a>
                        </div>
                    </form>
                </div>
                                </div>
                        </div>
<?php
}

if($action == 'update_lens_price'){
    $id = $_POST['id'];
    $addition_name = strtoupper($_POST['addition_name']);
    $material_name = $_POST['material_name'];
    $lens_type_name = $_POST['lens_type_name'];
    $spherical_lower = $_POST['spherical_lower'];
    $spherical_upper = $_POST['spherical_upper'];
    $cylindrical_lower = $_POST['cylindrical_lower'];
    $cylindrical_upper = $_POST['cylindrical_upper'];
    $lens_price = $_POST['lens_price'];

    $row = mysql_fetch_assoc(mysql_query("SELECT * FROM lens_price WHERE id='$id'"));
    $update = mysql_query("UPDATE lens_price SET additions='$addition_name',material='$material_name',lens_type='$lens_type_name',spherical_lower='$spherical_lower',spherical_upper='$spherical_upper',cylindrical_lower='$cylindrical_lower',cylindrical_upper='$cylindrical_upper',lens_price='$lens_price' WHERE id='$id'");
    if($update == TRUE){
        if(strtoupper($row['additions']) != $addition_name){
        mysql_query("INSERT INTO lens_types SET lens_name='$addition_name',parent_name='ADDITIONS'");
        }
        echo 'Lens Price Updated successfully!@@@success';
    }else{
        'The Lens Price might already exist!@@@error';
    }

}