public function paymentAction()
 {
     if ($this->request->isPost()) {
         $orderarray = $this->request->getPost('orderarray');
         $orderarray = json_decode($orderarray, TRUE);
         $sum = 0;
         foreach ($orderarray as $veg) {
             $sum += $veg[m_price] * $veg[quant];
         }
         //echo $sum;
         $auth = $this->session->get('auth');
         $id = $auth[uid];
         $orders = new Orders();
         $orders->u_id = $id;
         $orders->o_price = $sum;
         $orders->o_date = date("Y-m-d");
         $orders->o_payment = "Failed";
         $orders->o_delivery = 0;
         if ($orders->save() == false) {
             foreach ($orders->getMessages() as $message) {
                 echo $message;
             }
         } else {
             foreach ($orderarray as $veg) {
                 $orderdetails = new Orderdetails();
                 $orderdetails->o_id = $orders->o_id;
                 $orderdetails->m_id = $veg[m_id];
                 $orderdetails->od_quantity = $veg[quant];
                 $orderdetails->od_prepared = 0;
                 if ($orderdetails->save() == false) {
                     foreach ($orderdetails->getMessages() as $message) {
                         echo $message;
                     }
                 } else {
                     $user = Userdetails::findFirst(array("(u_id = :id:)", 'bind' => array('id' => $id)));
                     if ($user != false) {
                         $datename = $user->u_fname;
                         $dataemail = $user->u_email;
                         $dataphone = $user->u_phno;
                         $dataamount = $sum;
                         $url = "https://www.instamojo.com/slickaccount/test-for-integration-monthly-payment/?intent=buy&data_name=" . $dataname . "&data_email=" . $dataemail . "&data_phone=" . $dataphone . "&data_amount=" . $dataamount . "&data_readonly=data_phone&data_readonly=data_name&data_readonly=data_email";
                         header('Location: ' . $url);
                     }
                 }
             }
         }
     }
 }
    public function makeOrder()
    {
        $drawing_rights = 0;
        $ids = $_POST['kemsaCode'];
        $price = $_POST['price'];
        $open = $_POST['open'];
        $recepits = $_POST['receipts'];
        $issues = $_POST['issues'];
        $adjustments = $_POST['adjustments'];
        $losses = $_POST['losses'];
        $closing = $_POST['closing'];
        $nodays = $_POST['days'];
        $quantity = $_POST['quantity'];
        $comment = $_POST['comment'];
        $s_quantity = $_POST['actual_quantity'];
        $workload = $_POST['workload'];
        $order_no = $_POST['order_no'];
        $bed_capacity = $_POST['bed_capacity'];
        $historical_consumption = $_POST['historical'];
        $orderDate = date('y-m-d');
        $facilityCode = $facility_c = $this->session->userdata('news');
        $user_id = $facility_c = $this->session->userdata('user_id');
        $drawing_rights = $this->session->userdata('drawing_rights');
        $j = count($ids);
        $total = 0;
        $count = 1;
        $data_array = NULL;
        for ($i = 0; $i < $j; $i++) {
            if ($count == 1) {
                $data1 = array('orderDate' => '' . $orderDate . '', 'facilityCode' => '' . $facilityCode . '', 'drawing_rights' => '' . $drawing_rights . '', 'orderby' => '' . $user_id . '');
                $o = new Ordertbl();
                $o->fromArray($data1);
                $o->save();
                $lastId = Ordertbl::getNeworder($facilityCode);
                $newOrderid = $lastId->maxId;
                $count++;
            }
            if ($quantity[$i] >= 0) {
                $data = array("kemsa_code" => $ids[$i], "price" => $price[$i], "quantityOrdered" => $quantity[$i], "orderNumber" => $newOrderid, 't_receipts' => $recepits[$i], 't_issues' => $issues[$i], 'adjust' => $adjustments[$i], 'losses' => $losses[$i], 'days' => $nodays[$i], 'c_stock' => $closing[$i], 'comment' => $comment[$i], 's_quantity' => $s_quantity[$i], 'workload' => $workload, 'bed_capacity' => $bed_capacity, 'order_no' => $order_no, 'o_balance' => $open[$i], 'historical_consumption' => $historical_consumption[$i]);
                $total = $quantity[$i] * $price[$i] + $total;
                $u = new Orderdetails();
                $u->fromArray($data);
                $u->save();
            }
            ////////////////////////////////////////////////////////////////////////////////////////
        }
        $myobj = Doctrine::getTable('Ordertbl')->find($newOrderid);
        $myobj->orderTotal = $total;
        $myobj->orderby = $user_id;
        $myobj->workload = $workload;
        $myobj->bedcapacity = $bed_capacity;
        $myobj->order_no = $order_no;
        $myobj->save();
        $in = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAll("SELECT a.category_name, b.drug_name, b.kemsa_code, b.unit_size, b.unit_cost, \n\t\tc.quantityOrdered, c.price, c.orderNumber, c.quantityRecieved,\n\t\tc.o_balance, c.t_receipts, c.t_issues, c.adjust, c.losses, c.days, c.comment, c.c_stock,c.s_quantity\nFROM drug_category a, drug b, orderdetails c\nWHERE c.orderNumber ={$newOrderid}\nAND b.id = c.kemsa_code\nAND a.id = b.drug_category\nORDER BY a.id ASC , b.drug_name ASC ");
        $jay = count($in);
        $from_ordertbl = Ordertbl::get_order($newOrderid);
        //create the report title
        $html_title = "<div ALIGN=CENTER><img src='Images/coat_of_arms.png' height='70' width='70'style='vertical-align: top;' > </img></div>\n      <div style='text-align:center; font-size: 14px;display: block;font-weight: bold;'>Order Report</div>\n       <div style='text-align:center; font-family: arial,helvetica,clean,sans-serif;display: block; font-weight: bold; font-size: 14px;'>\n       Ministry of Health</div>\n        <div style='text-align:center; font-family: arial,helvetica,clean,sans-serif;display: block; font-weight: bold;display: block; font-size: 13px;'>Health Commodities Management Platform</div><hr />   ";
        //get the facility name and MFL code
        foreach ($from_ordertbl as $order) {
            $o_date = $order->orderDate;
            $a_date = $order->approvalDate;
            $o_total = $order->orderTotal;
            $d_rights = $order->drawing_rights;
            $bal = $d_rights - $o_total;
            $creator = $order->orderby;
            $approver = $order->approveby;
            foreach ($order->Code as $f_name) {
                $fac_name = $f_name->facility_name;
            }
            $mfl = $order->facilityCode;
            $myobj = Doctrine::getTable('Facilities')->findOneByfacility_code($mfl);
            $diasto = $myobj->district;
            $myobj1 = Doctrine::getTable('Districts')->find($diasto);
            $disto_name = $myobj1->district;
            $county = $myobj1->county;
            $myobj2 = Doctrine::getTable('Counties')->find($county);
            $county_name = $myobj2->county;
            $myobj_order = Doctrine::getTable('User')->find($creator);
            $creator_name = $myobj_order->email;
            $creator_name1 = $myobj_order->fname;
            $creator_name2 = $myobj_order->lname;
            $creator_telephone = $myobj_order->telephone;
        }
        //create the table for displaying the order details
        $html_body = "<table class='data-table' width=100%>\n<tr>\n<td>MFL No: {$mfl}</td> \n<td >Health Facility Name:<br/> {$fac_name}</td>\n<td >Total OPD Visits & Revisits: </td>\n<td >Level:</td>\n<td>Dispensary</td>\n<td >Health Centre</td>\n</tr>\n<tr>\n<td>County: {$county_name}</td> \n<td > District: {$disto_name}</td>\n<td >In-patient Bed Days : </td>\n<td >Order Date:<br/> " . date('d M, Y', strtotime($o_date)) . " </td>\n<td>Order no.</td>\n<td >Reporting Period <br/>\nStart Date:  <br/>  End Date: " . date('d M, Y', strtotime($o_date)) . "\n</td>\n</tr>\n</table>";
        $html_body .= "<style>table.data-table {border: 1px solid #DDD;margin: 10px auto;border-spacing: 0px;}\ntable.data-table th {border: none;color: #036;text-align: center;background-color: \t#FFF380;border: 1px solid #DDD;border-top: none;max-width: 450px;}\ntable.data-table td, table th {padding: 4px;}\ntable.data-table td {border: none;border-left: 1px solid #DDD;border-right: 1px solid #DDD;height: 30px;margin: 0px;border-bottom: 1px solid #DDD;}\n</style>\n<table class='data-table'>\n\n\n<thead><tr><th><b>KEMSA Code</b></th><th><b>Description</b></th><th><b>Order Unit Size</b></th><th><b>Order Unit Cost</b></th><th ><b>Opening Balance</b></th>\n<th ><b>Total Receipts</b></th><th><b>Total issues</b></th><th><b>Adjustments</b></th><th><b>Losses</b></th><th><b>Closing Stock</b></th><th><b>No days out of stock</b></th>\n<th><b>Order Quantity (Packs)</b></th><th><b>Order Quantity (Actual Units)</b></th><th><b>Order cost(Ksh)</b></th><th><b>Comment</b></th></tr> </thead><tbody>";
        $html_body .= '<ol type="a">';
        for ($i = 0; $i < $jay; $i++) {
            if ($i == 0) {
                $html_body .= '<tr style="background-color:#C6DEFF;"> <td colspan="15" >
				 <li> ' . $in[$i]['category_name'] . ' </li> </td></tr>';
            } else {
                if ($in[$i]['category_name'] != $in[$i - 1]['category_name']) {
                    $html_body .= '<tr style="background-color:#C6DEFF;"> <td  colspan="15"> 
       	 	<li> ' . $in[$i]['category_name'] . ' </li> </td></tr>';
                }
            }
            $adj = $in[$i]['adjust'];
            $c_stock = $in[$i]['c_stock'];
            $o_t = $in[$i]['quantityOrdered'];
            $o_q = $in[$i]['price'];
            $o_bal = $in[$i]['o_balance'];
            $t_re = $in[$i]['t_receipts'];
            $t_issues = $in[$i]['t_issues'];
            $losses = $in[$i]['losses'];
            if ($o_bal == 0 && $t_re == 0 && $t_issues > 0) {
                $adj = $t_issues;
            }
            $c_stock = $o_bal + $t_re + $adj - $losses - $t_issues;
            if ($c_stock < 0) {
                $adj = $c_stock * -1;
            }
            $c_stock = $o_bal + $t_re + $adj - $losses - $t_issues;
            $html_body .= "<tr>";
            $html_body .= "<td>" . $in[$i]['kemsa_code'] . "</td>";
            $html_body .= "<td>" . $in[$i]['drug_name'] . "</td>";
            $html_body .= "<td>" . $in[$i]['unit_size'] . "</td>";
            $ot = number_format($o_t * $o_q, 2, '.', ',');
            $order_total = $order_total + $o_t * $o_q;
            $html_body .= "<td>{$o_q}</td>";
            $html_body .= "<td>" . $o_bal . "</td>";
            $html_body .= "<td>" . $t_re . "</td>";
            $html_body .= "<td>" . $t_issues . "</td>";
            $html_body .= "<td>" . $adj . "</td>";
            $html_body .= "<td>" . $losses . "</td>";
            $html_body .= "<td>" . $c_stock . "</td>";
            $html_body .= "<td>" . $in[$i]['days'] . "</td>";
            $html_body .= "<td>{$o_t}</td>";
            $html_body .= "<td>" . $in[$i]['s_quantity'] . "</td>";
            $html_body .= "<td>{$ot}</td>";
            $html_body .= "<td>" . $in[$i]['comment'] . "</td></tr>";
        }
        $myobj_approve = Doctrine::getTable('User')->find($approver);
        $approve_name = $myobj_approve->email;
        $approve_name1 = $myobj_approve->fname;
        $approve_name2 = $myobj_approve->lname;
        $approve_telephone = $myobj_approve->telephone;
        $bal = $d_rights - $order_total;
        $html_body .= '</tbody></table></ol>';
        $html_body1 = '<table class="data-table" width="100%" style="background-color: 	#FFF380;">
		  <tr style="background-color: 	#FFFFFF;" > <td colspan="4" ><div style="float: left" > Total Order Value:</div><div style="float: right" >KSH ' . number_format($order_total, 2, '.', ',') . '</div> </td></tr>
		   <tr style="background-color: 	#FFFFFF;"  > <td colspan="4" ><div style="float: left" > Drawing Rights Available Balance:</div><div style="float: right" >KSH		' . number_format($bal, 2, '.', ',') . '</div> </td></tr>
		   <tr><td>FACILITY TEL NO:</td><td colspan="3">FACILITY EMAIL:</td>
		   </tr>
		   <tr><td >Prepared by (Name/Designation) ' . $creator_name1 . ' ' . $creator_name2 . '
		   <br/>
		   <br/>Email: ' . $creator_name . '</td><td>Tel: ' . $creator_telephone . '</td><td>Date: ' . date('d M, Y', strtotime($o_date)) . '</td><td>Signature</td>
		   </tr>
		   <tr><td>Checked by (Name/DPF/DPHN)
		   <br/>
		   <br/>Email</td><td>Tel</td><td>Date</td><td>Signature</td>
		   </tr>
		   <tr><td>Authorised by (Name/DMoH) Pending
		   <br/>
		   <br/>Email: Pending </td><td>Tel: Pending </td><td>Date: Pending </td><td>Signature</td>
		   
		   </tr>
		   </table>';
        //now ganerate an order pdf from the generated report
        $this->mpdf = new mPDF('', 'A4-L', 0, '', 15, 15, 16, 16, 9, 9, '');
        $this->mpdf->WriteHTML($html_title);
        $this->mpdf->defaultheaderline = 1;
        $this->mpdf->simpleTables = true;
        $this->mpdf->WriteHTML($html_body);
        $this->mpdf->AddPage();
        $this->mpdf->WriteHTML($html_body1);
        $report_name = $fac_name . 'facility_order_no_' . $order_no . "order_date" . date('d-m-y');
        if (!write_file('./pdf/' . $report_name . '.pdf', $this->mpdf->Output('$report_name', 'S'))) {
            $this->session->set_flashdata('system_error_message', 'An error occured but the order was placed contact support team');
            redirect("order_approval/district_orders");
            //   $this->district_orders();
        } else {
            $message_1 = '<br>Please find the Order Made by ' . $fac_name . ' below for approval.
		<br>
		You may log in to the HCMP system to approve it.<a href="http://health-cmp.or.ke/" target="_blank">Click here</a>
		<br>
		<br>
		<br>';
            $subject = 'Pending Approval Order Report For ' . $fac_name;
            $attach_file = './pdf/' . $report_name . '.pdf';
            $message = $message_1 . $html_title . $html_body . $html_body1;
            $response = $this->send_order_submission_email($message, $subject, $attach_file, null);
            if ($response) {
                delete_files('./pdf/' . $report_name . '.pdf');
            } else {
                //do nothing
            }
        }
        $this->send_order_sms();
        $this->session->set_flashdata('system_success_message', 'Your order has been saved');
        redirect('Order_Management/#tabs-1');
    }