<?php
error_reporting(0);
if (!isset($_SESSION)) {
    session_start();
}

include('accesscheck2.php');
require_once('Connections/courier.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'];
$insurance_company_id = $_POST['insurer'];
$date = date('Y-m-d H:i:s');

$ins_company = $_POST['ins_company'];
$mode_of_payment_all = $_POST['mode_of_payment_all'];
$provider_id = $_SESSION['provider_id'];
$member_no = $_POST['member_no'];
$user_id = $_SESSION['myMM_Userid'];
$process_claim_no = $_POST['process_claim_no'];
$provider_ref_no = $_POST['provider_ref_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'];



////////////Cashier Payments////////////
if ($action == 'make_payments') {
    $payment_status = 'Paid';
    $characters = array("A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    $PASSSALT = $characters[rand(0, 32)] . $characters[rand(0, 32)];
    $today = date('dmy/his');
    $next_location = $_POST['next_location'];
    $payment_type_approve = $_POST['payment_type_approved'];
    $process_claim_no = $_POST['process_claim_no'];

    if ($payment_type_approve == 'Part-Payment') {
        $amount = $_POST['amount_tendered'];
        if ($amount >= $_POST['amount_to_pay']) {
            $amount = $_POST['amount_to_pay'];
        }
        $total_amt_to_pay = $_POST['amount_to_pay'];
        $amt_left_to_pay = $total_amt_to_pay - $amount;
    } else {
        $amount = $_POST['amount_to_pay'];
    }

    $total_bill = $_POST['total_bill'];
    $total_vatnhil = $_POST['total_vatnhil'];
    $total_total_amount = $_POST['total_total_amount'];
    $amount_deducted = $_POST['amount_to_deduct'];
    $previous_balance = $_POST['current_balance'];
    $new_balance = $_POST['new_balance'];
    $amount_tendered1 = $_POST['amount_tendered'];

    $amount_tendered2 = $_POST['amount_tendered1'];
    $posAmount = $_POST['posAmount'];
    $chequeAmount = $_POST['chequeAmount'];
    $MoMoAmount = $_POST['MoMoAmount'];
    $multiPayment = $amount_tendered2 + $posAmount + $chequeAmount + $MoMoAmount;

    $checkbox = $_POST['multiplePaymentRadio'];
    ///////////////// check if payment type is multiple or single /////////////////////
    $amount_tendered =  ($checkbox == 'multiPayment') ? $multiPayment : $amount_tendered1;

    $amount_change = $_POST['amount_for_change'];
    $total_price_cash = $_POST['total_price_cash'];

    $patient_no = $_POST['patient_no'];
    $patient_name = $_POST['patient_name'];
    $type_of_patient = $_POST['type_of_patient'];
    $receiptno = $receipt_number;
    $cashier_user = $_SESSION['myMM_Userid'];
    $cashier_name = $_SESSION['myMM_Fullname'];
    $pay_by = $_POST['pay_by'];

    if ($checkbox == 'multiplePaymentRadio'){
        $bank = $_POST['bank1'];
        $cheque_no = $_POST['checkno1'];
        $cardname = $_POST['cardname1'];
        $transaction_id = $_POST['transaction_id1'];

        if($pay_by == 'Mobile Money'){
            $bank = $_POST['mobile_phone_name1'];
            $cheque_no = $_POST['mobile_phone_no1'];
        }

    }else{
        $bank = $_POST['bank'];
        $cheque_no = $_POST['checkno'];
        $cardname = $_POST['cardname'];
        $transaction_id = $_POST['transaction_id'];
        if($pay_by == 'Mobile Money'){
            $bank = $_POST['mobile_phone_name'];
            $cheque_no = $_POST['mobile_phone_no'];
        }
    }




    $item_trans_id = $_POST['item_trans_id'];
    $receipt_number = $_SESSION['branch_code']. "/" . $PASSSALT . "/" . $today;



    $current_location = $next_location;
    if ($next_location == "") {
        $action_status = '';
    } else {
        $action_status = 'Sent to ' . $current_location;
    }

    if(count($item_trans_id>0)){
    foreach ($item_trans_id as $itemtransid) {
        $check_credit_sales = mysql_fetch_assoc(mysql_query("SELECT mode_of_payment, payment_status FROM claims_details WHERE id='$itemtransid'"));
        $mode_of_payment = $check_credit_sales['mode_of_payment'];
        $payment_status2 = $check_credit_sales['payment_status'];
        if($mode_of_payment=='credit sales' && $payment_status2=='Approved') {
            $rsinsert = mysql_query("update claims_details set payment_status='Approved-Paid', cashier_user='$cashier_user',receipt_number='$receipt_number',date_of_payment='$date' where id='$itemtransid' AND comment='Credit Sales Payment' AND payment_status='Approved';", $courier) or die(mysql_error($courier));
        } else if($payment_status2=='Owing') {
            $rsinsert = mysql_query("update claims_details set payment_status='$payment_status', cashier_user='$cashier_user',receipt_number='$receipt_number',date_of_payment='$date' where id='$itemtransid';", $courier) or die(mysql_error($courier));
        }
    }
}

    $tday = date('Y-m-d');
    if ($payment_type_approve == 'Part-Payment') {
        if ($previous_balance >= 0) {
            $new_balance = $previous_balance - $amount_deducted - $amt_left_to_pay;
        } else {
            $new_balance = -$amt_left_to_pay;
        }
    } else {
        if ($previous_balance >= 0) {
            $new_balance = $previous_balance - $amount_deducted;
        } else {
            $new_balance = 0;
        }
    }

    $query_insert = "INSERT INTO `cashier_payments` (`id`, `patient_no`, `type_of_patient`, `receiptno`, `date_added`, `date_added_short`,`cashier_user`, `cashier_name`, `amount`, `pay_by`, `bank`, `cheque_no`, `cardname`, `transaction_id`, `outstanding_balance`, `process_claim_no`, `total_bill`, `amount_deducted`, `previous_balance`, `new_balance`, `amount_tendered`, `amount_change`, `payment_type_approve`,`branch_id`) VALUES (NULL, '$patient_no', '$type_of_patient', '$receipt_number', CURRENT_TIMESTAMP,'$tday', '$cashier_user', '$cashier_name', '$amount', '$pay_by', '$bank', '$cheque_no', '$cardname', '$transaction_id', '$outstanding_balance', '$process_claim_no', '$total_bill', '$amount_deducted', '$previous_balance', '$new_balance', '$amount_tendered', '$amount_change', '$payment_type_approve','".$_SESSION['branch_id']."');";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error($courier));
    mysql_query("update  patient_information set patient_balance='$new_balance' where card_number='$patient_no';");
    mysql_query("UPDATE patient_visit_discounts SET discount_used='used' WHERE discount_used='not used' AND discount_status='Approved' AND process_claim_no='$process_claim_no'");

    $query_insert = "update claims_details set current_location='$current_location', action_status='$action_status' where receipt_number='$receipt_number' AND  process_claim_no='$process_claim_no'";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error($courier));

    $check = mysql_query("select * from process_claim_no where process_claim_no = '$process_claim_no' and consulting_room_status='awaiting'", $courier);
    if (mysql_num_rows($check) > 0) {
        $query_insert = "update process_claim_no set session_status='$current_location',consulting_room_status='pending' where  process_claim_no='$process_claim_no'";
    } else {
        $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($courier));
    include('view_items_claims_cashier_print.php');
}


if ($action == 'make_deposit_refund') {
    $payment_status = 'Paid';
    $cashier_user = $_SESSION['myMM_Fullname'];
    $characters = array("A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    $PASSSALT = $characters[rand(0, 32)] . $characters[rand(0, 32)];
    $today = date('dmy/his');

    $amount_tendered = $_POST['amount_tendered'];
    $amount = $amount_tendered;
    $transaction_type = $_POST['transaction_type'];

    $patient_no = $_POST['patient_no'];
    $patient_name = $_POST['patient_name'];
    $type_of_patient = $_POST['type_of_patient'];
    $receiptno = $receipt_number;
    $cashier_user = $_SESSION['myMM_Userid'];
    $cashier_name = $_SESSION['myMM_Fullname'];
//$amount=$amount_tendered;
    $pay_by = $_POST['pay_by'];
    $bank = $_POST['bank'];
    $cheque_no = $_POST['checkno'];
    $cardname = $_POST['cardname'];
    $transaction_id = $_POST['transaction_id'];

    $receipt_number = $patient_no . "/" . $PASSSALT . "/" . $today;

    $query_rsodest_patient = "SELECT * FROM patient_information where card_number='$patient_no'";
    $rsodest_patient = mysql_query($query_rsodest_patient, $courier) or die(mysql_error($courier));
    $row_rsodest_patient = mysql_fetch_assoc($rsodest_patient);

    if ($transaction_type == 'deposit') {
        $previous_balance = $row_rsodest_patient['patient_balance'];
        $new_balance = $previous_balance + $amount_tendered;
    }

    if ($transaction_type == 'refund') {
        $previous_balance = $row_rsodest_patient['patient_balance'];
        $new_balance = $previous_balance - $amount_tendered;
    }

    $tday = date('d-m-Y');

    $query_insert = "INSERT INTO `cashier_payments` (`id`, `patient_no`, `type_of_patient`, `receiptno`, `date_added`, `date_added_short`,`cashier_user`, `cashier_name`, `amount`, `pay_by`, `bank`, `cheque_no`, `cardname`, `transaction_id`, `outstanding_balance`, `process_claim_no`, `total_bill`, `amount_deducted`, `previous_balance`, `new_balance`, `amount_tendered`, `amount_change`, `transaction_type`) VALUES (NULL, '$patient_no', '$type_of_patient', '$receipt_number', CURRENT_TIMESTAMP,'$tday', '$cashier_user', '$cashier_name', '$amount', '$pay_by', '$bank', '$cheque_no', '$cardname', '$transaction_id', '$outstanding_balance', '$process_claim_no', '$total_bill', '$amount_deducted', '$previous_balance', '$new_balance', '$amount_tendered', '$amount_change', '$transaction_type');";
//echo $query_insert;	
//exit;

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


    mysql_query("update  patient_information set patient_balance='$new_balance' where card_number='$patient_no';");


    include('view_deposit_refund_cashier_print.php');
}

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 width="100%" border="0" cellpadding="1" cellspacing="1" class="sectionText1" id="membershipinfo2">
        <tbody>
            <tr>
                <td height="25" colspan="2" valign="middle" style="color: #FFFFFF; background-color: #611001;cursor: pointer;" class="baseborder"><i class="icon-user"></i> Payment Details</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <table width="100%" cellpadding="1" cellspacing="1" class="table table-hover table-striped table-bordered">
                        <thead>
                            <tr>
                                <th style="background-color: #FBB;color: #000; font-weight:bold" class="count">&nbsp;</th>
                                <th style="background-color: #FBB;color: #000; font-size:12px;" >Item</th>
                                <th style="background-color: #FBB;color: #000; font-size:12px;">Amount:</th>
                                <th style="background-color: #FBB;color: #000; font-size:12px;">Status</th>
                            </tr>
                        </thead>
                        <tbody>
    <?php if ($totaldetails > 0) { ?>
        <?php
        do {
            $start_row = $start_row + 1;
            ?>
                                    <tr <?php
            if (fmod($start_row, 2) > 0) {
                echo 'class="odd"';
            } else {
                echo 'style="background: linen"';
            }
            ?>>
                                        <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 $rs_get_details['total_price']; ?></td>
                                        <td valign="top" style="cursor: pointer;"><?php echo $rs_get_details['payment_status']; ?></td>

                                    </tr>

                                    <?php } while ($rs_get_details = mysql_fetch_assoc($get_payment_details)); ?>

    <?php } else { ?>
                                <tr <?php
        if (fmod($start_row, 2) > 0) {
            echo 'class="odd"';
        } else {
            echo 'style="background: linen"';
        }
        ?>>
                                    <td height="23" colspan="6" valign="top" class="count">Sorry, No Payment Records found</td>
                                </tr>

                            <?php } ?>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>    

                            <?php
                        }



                        if ($action == "delete_notes") {
                            $del = mysql_query("DELETE FROM cashier_notes where id='$id'");
                            include("cashier/note_deposits.php");
                        }
