"1","name"=>"Books/Magazines","type"=>"1"), array("id"=>"2","name"=>"Car & Transportation","type"=>"1"), array("id"=>"3","name"=>"Charities","type"=>"1"), array("id"=>"4","name"=>"Child care","type"=>"1"), array("id"=>"5","name"=>"Clothing","type"=>"1"), array("id"=>"6","name"=>"Debt Interest","type"=>"1"), array("id"=>"7","name"=>"Debt Reduction","type"=>"1"), array("id"=>"8","name"=>"Education/Tution Fee","type"=>"1"), array("id"=>"9","name"=>"Events","type"=>"1"), array("id"=>"10","name"=>"Food","type"=>"1"), array("id"=>"11","name"=>"General Expense","type"=>"1"), array("id"=>"12","name"=>"Gifts","type"=>"1"), array("id"=>"13","name"=>"Household Items/Supplies","type"=>"1"), array("id"=>"14","name"=>"Household Repairs","type"=>"1"), array("id"=>"15","name"=>"Income/Other Tax","type"=>"1"), array("id"=>"16","name"=>"Insurance","type"=>"1"), array("id"=>"17","name"=>"Lending","type"=>"1"), array("id"=>"18","name"=>"Medical/Health","type"=>"1"), array("id"=>"19","name"=>"Mortgage","type"=>"1"), array("id"=>"20","name"=>"Others","type"=>"1"), array("id"=>"21","name"=>"Personal","type"=>"1"), array("id"=>"22","name"=>"Pet Food/Treats","type"=>"1"), array("id"=>"23","name"=>"Recreation and Fitness","type"=>"1"), array("id"=>"24","name"=>"Rent","type"=>"1"), array("id"=>"25","name"=>"Savings","type"=>"1"), array("id"=>"26","name"=>"Sports","type"=>"1"), array("id"=>"27","name"=>"Utilities","type"=>"1"), array("id"=>"28","name"=>"Vacation","type"=>"1"), array("id"=>"29","name"=>"Bank Interest","type"=>"2"), array("id"=>"30","name"=>"Borrowing","type"=>"2"), array("id"=>"31","name"=>"Business","type"=>"2"), array("id"=>"32","name"=>"Consultancy","type"=>"2"), array("id"=>"33","name"=>"Contract","type"=>"2"), array("id"=>"34","name"=>"Lending Back","type"=>"2"), array("id"=>"35","name"=>"Others","type"=>"2"), array("id"=>"36","name"=>"Personal","type"=>"2"), array("id"=>"37","name"=>"Rent","type"=>"2"), array("id"=>"38","name"=>"Salary","type"=>"2"), array("id"=>"39","name"=>"Stock Market/Divident","type"=>"2"), array("id"=>"40","name"=>"Transport Business","type"=>"2") ); return $category; } function index() { $this->layout="visitor"; $urlLArray = explode('/',$this->here); $uniqueURL = end($urlLArray); $expenseType = substr($uniqueURL, 0, 1); $this->Session->write("current_unique_url",$uniqueURL); $skipMobileOption= $this->Session->read("skip_mobile_option"); if($this->Session->check("skip_mobile_option")){ $this->Session->delete("skip_mobile_option"); } $this->set('unique_url',$uniqueURL); //if the request comes from mobile device then forward it to the mobile controller $detect = new MobileDetectComponent(); if ($detect->isMobile() && $skipMobileOption != "yes" ) { $this->redirect(array('controller'=> 'm','action'=>'/')); exit; } else { if($expenseType == "1" || $expenseType == "2" || $expenseType == "3"){ $this->render('expense'); } else { $this->render('expense_demo'); } } } function loadTab($uniqueURL) { $expenseType = ""; $this->layout=""; $just_created_new = false; if ($this->Session->check('just_created')){ $this->set("justCreated",$this->Session->read('just_created')); $this->Session->delete("just_created"); $just_created_new = true; } else { $this->set("justCreated",""); } if(isset($uniqueURL) && $uniqueURL != ""){ $expenseType = trim(substr($uniqueURL, 0, 1)); if($expenseType == "1" || $expenseType == "2"){ $data = $this->Expense->getGroupExpenseInfoByURL($uniqueURL); } else if($expenseType == "3"){ $data = $this->Expense->getFamilyExpenseInfoByURL($uniqueURL); if(!empty($data)){ $data["Category"] = $this->getCategories(); } } if (!$this->Session->check('Config.language') && !$this->Cookie->check('Config.expcount.language')) { $this->Session->write("Config.language",$data["Expense"]["language"]); $this->Cookie->write("Config.expcount.language",$data["Expense"]["language"]); } if(!empty($data)){ //insert data into the table access_infos $accessInfoData["id"] = $data["Expense"]["id"]; $accessInfoData["unique_url"] = $data["Expense"]["unique_url"]; $accessInfoData["access_time"] = $this->getSystemCurrentTimeStamp(); $error = $this->AccessInfo->saveAccessInfo($accessInfoData); //insert loading history $loginHistory['expense_id'] = $accessInfoData["id"]; $loginHistory['unique_url'] = $accessInfoData["unique_url"]; $loginHistory['ip'] = $this->getClientIp();; $loginHistory['user_agent'] = $this->getUserAgent();; $loginHistory['create_date'] = $accessInfoData["access_time"]; $error = $this->LoadingHistory->insertLoadingHistory($loginHistory); $this->set("expenseData",json_encode($data)); $this->set("expenseData",json_encode($data)); /* $loginHistory["expense_id"] = $data["Expense"]["id"]; $loginHistory["remote_ip"] = $_SERVER['REMOTE_ADDR']; if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ $loginHistory["forward_ip"] = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $loginHistory["forward_ip"] = ""; } $loginHistory["country"] = "";//ip_info($loginHistory["remote_ip"], "Country Code"); //$userLocation = ip_info($loginHistory["remote_ip"], "Location"); $loginHistory["location"] = "";//$userLocation["city"].",".$userLocation["state"]; $loginHistory["is_login"] = "0"; $loginHistory["user_id"] = ""; $loginHistory["source"] = $_SERVER['HTTP_USER_AGENT']; */ } } $this->set("uniqueURL",$uniqueURL); //set relevant view if($expenseType == "1"){ $this->loadGroupExpense(); } else if($expenseType == "2") { $this->loadMessExpense(); } else if($expenseType == "3") { $this->loadFamilyExpense(); } else { $this->loadNotFound(); } if($just_created_new == true){ if ($this->Session->check('just_created_email')){ $data['Expense']["email"] = $this->Session->read('just_created_email'); $this->sendInstantEmail($data['Expense']); } } } function loadTabDemo($uniqueURL) { $this->layout=""; if ($this->Session->check('just_created')){ $this->set("justCreated",$this->Session->read('just_created')); $this->Session->delete("just_created"); } else { $this->set("justCreated",""); } if(isset($uniqueURL) && $uniqueURL != ""){ $expenseType = substr($uniqueURL, 0, 1); if($expenseType == "6" || $expenseType == "7"){ $demoData = $this->DemoExpense->getDemoGroupExpenseInfoByURL($uniqueURL); $data["Expense"] = $demoData["DemoExpense"]; $data["Participant"] = $demoData["DemoParticipant"]; $data["GroupExpense"] = $demoData["DemoGroupExpense"]; if($expenseType == "7"){ $data["Meal"] = $demoData["DemoMeal"]; } } else if($expenseType == "8"){ $demodata = $this->DemoExpense->getDemoFamilyExpenseInfoByURL($uniqueURL); $data["Expense"] = $demodata["DemoExpense"]; $data["FamilyExpense"] = $demodata["DemoFamilyExpense"]; $data["Category"] = $this->getCategories(); } if (!$this->Session->check('Config.language') && !$this->Cookie->check('Config.expcount.language')) { $this->Session->write("Config.language",$data["Expense"]["language"]); $this->Cookie->write("Config.expcount.language",$data["Expense"]["language"]); } if(!empty($data)){ $this->set("expenseData",json_encode($data)); $loginHistory["expense_id"] = $data["Expense"]["id"]; $loginHistory["remote_ip"] = $_SERVER['REMOTE_ADDR']; if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ $loginHistory["forward_ip"] = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $loginHistory["forward_ip"] = ""; } $loginHistory["country"] = "";//ip_info($loginHistory["remote_ip"], "Country Code"); //$userLocation = ip_info($loginHistory["remote_ip"], "Location"); $loginHistory["location"] = "";//$userLocation["city"].",".$userLocation["state"]; $loginHistory["is_login"] = "0"; $loginHistory["user_id"] = ""; $loginHistory["source"] = $_SERVER['HTTP_USER_AGENT']; } if($expenseType == "6"){ $this->loadGroupExpenseDemo(); } else if($expenseType == "7") { $this->loadMessExpenseDemo(); } else if($expenseType == "8") { $this->loadFamilyExpenseDemo(); } else { $this->loadNotFound(); } } } public function loadNotFound() { } public function sendEmail(){ if($this->request->is('ajax')){ $data = array(); $data["email"] = $this->data["Expense"]["email"]; $data["expense_title"] = $this->data["Expense"]["emailExpenseTitle"]; $data["unique_url"] = $this->data["Expense"]["emailUniqueURL"]; $this->sendEmailMethod($data); } exit; } public function sendMyExpenseEmail(){ if($this->request->is('ajax')){ $data = array(); $data["email"] = $this->data["email"]; $data["expense_title"] = $this->data["expense_title"]; $data["unique_url"] = $this->data["unique_url"]; $this->sendEmailMethod($data); } exit; } public function sendInstantEmail($value) { $emailData = array(); $emailData["expense_title"] = $value["title"]; $emailData["unique_url"] = $value["unique_url"]; $emailData["email"] = $value["email"]; //send email $this->sendEmailMethod($emailData); //insert into ExpenseEmail $inputData = array(); $inputData["unique_url"] = $value["unique_url"]; $inputData["email"] = $value["email"]; $inputData["title"] = $value["title"]; $inputData["count_email_attempt"] = 1; $this->loadModel('ExpenseEmail'); $this->ExpenseEmail->insertExpenseEmail($inputData); } public function sendEmailMethod($data) { //insert record into the table email_histories $emailHistory['unique_url'] = $data["unique_url"]; $emailHistory['sent_to'] = $data["email"]; $emailHistory['ip'] = $this->getClientIp(); $emailHistory['create_date'] = $this->getSystemCurrentTimeStamp(); $error = $this->EmailHistory->insertEmailHistory($emailHistory); $default = array( 'host' => Configure::read('expensecount.email.smtp.host'), 'port' => 25, 'auth' => 'plain', 'username' => Configure::read('expensecount.email.smtp.username'), 'password' => Configure::read('expensecount.email.smtp.password'), 'tsl' => false, 'transport' => 'smtp', 'from' => array(Configure::read('expensecount.email.smtp.from') => 'ExpenseCount'), 'returnPath' => Configure::read('expensecount.email.smtp.from'), 'layout' => false, 'emailFormat' => 'html', //'template' => 'only_text', 'charset' => 'utf-8', 'headerCharset' => 'utf-8', ); App::uses('CakeEmail', 'Network/Email'); //echo $Email-> $Email = new CakeEmail(); $Email->to($data["email"]); $Email->emailFormat('html'); $Email->template('email',null)->viewVars( array('data' => $data)); $Email->subject('ExpenseCount "'.$data["expense_title"].'" '); $Email->replyTo(Configure::read('expensecount.email.smtp.from')); $Email->from(array(Configure::read('expensecount.email.smtp.from') => "ExpenseCount.com")); $Email->smtpOptions = $default; $Email->delivery = 'smtp'; try { $Email->send(); } catch (Exception $e) { } } public function sendHtmlEmail($dest=null, $aMsg=null) { $Email = new CakeEmail('gmail'); $Email->to($dest); $Email->emailFormat('html'); $Email->template('email')->viewVars( array('aMsg' => $aMsg)); $Email->subject('Email from ExpenseCount'); $Email->replyTo('admin@expensecount.com'); $Email->from ('admin@gmail.com'); return ; } public function changeGroupExpense(){ if($this->request->is('ajax')){ $data = array(); $option = $this->data["isAdd"]; if(isset($this->data["expenseType"])){ $data["expense_type"] = $this->data["expenseType"]; } if($option == "1" || $option == "2" || $option == "3"){ $data["id"] = $this->data["id"]; $data["expense_id"] = $this->data["expenseId"]; $data["what"] = $this->data["expenseName"]; $data["expense_date"] = $this->data["expenseDate"]; $data["amount"] = $this->data["amount"]; $data["paid_by_participant_id"] = $this->data["paidBy"]; $data["participant_amount"] = $this->data["participantAmountStr"]; $data["isDetails"] = $this->data["isDetails"]; $data["isAdd"] = $this->data["isAdd"]; $data["type"] = $this->data["type"]; if($data["isAdd"] == "1"){ $data["is_reimbursement"] = $this->data["isreimburse"]; $data["expense_date_old"] = $this->getStrToIntDate($data["expense_date"]); $message = $this->GroupExpense->addGroupExpense($data); } else if($data["isAdd"] == "2") { $data["is_reimbursement"] = $this->data["isreimburse"]; $data["previous_desc"] = $this->data["previousDesc"]; $data["new_desc"] = $this->data["newDesc"]; $data["previous_paid_by"] = $this->data["previousPaidBy"]; $data["expense_date_old"] = $this->getStrToIntDate($data["expense_date"]); $message = $this->GroupExpense->modifyGroupExpense($data); } else if($data["isAdd"] == "3") { $data["previous_desc"] = $this->data["previousDesc"]; $data["new_desc"] = $this->data["newDesc"]; $data["previous_paid_by"] = $this->data["previousPaidBy"]; $message = $this->GroupExpense->deleteGroupExpense($data); } else if($data["isAdd"] == "4"){ $uniqueURL = $this->data["expenseId"]; $data = $this->Expense->getGroupExpenseInfoByURL($uniqueURL); } } else if($option == "5" || $option == "6" || $option == "7"){ $data["id"] = $this->data["id"]; $data["expense_id"] = $this->data["expenseId"]; $data["date"] = $this->data["date"]; $data["isAdd"] = $this->data["isAdd"]; $data["meal_amount"] = $this->data["participantMealStr"]; if($data["isAdd"] == "5"){ $data["date_old"] = $this->getStrToIntDate($data["date"]); $message = $this->Meal->addMeal($data); } else if($data["isAdd"] == "6") { $data["old_date"] = $this->data["oldDate"]; $data["date_old"] = $this->getStrToIntDate($data["date"]); $message = $this->Meal->modifyMeal($data); } else if($data["isAdd"] == "7") { $message = $this->Meal->deleteMeal($data); } else if($data["isAdd"] == "4"){ $uniqueURL = $this->data["expenseId"]; $data = $this->Expense->getGroupExpenseInfoByURL($uniqueURL); } } else if($option == "8" || $option == "9" || $option == "10" ){ $data["id"] = $this->data["id"]; $data["expense_id"] = $this->data["expenseId"]; $data["record_type"] = $this->data["recordType"]; $data["what"] = $this->data["expenseName"]; $data["category"] = $this->data["expenseCategory"]; $data["expense_date"] = $this->data["expenseDate"]; $data["amount"] = $this->data["amount"]; $data["isAdd"] = $this->data["isAdd"]; $data["type"] = $this->data["type"]; if($data["isAdd"] == "8"){ $data["expense_date_old"] = $this->getStrToIntDate($data["expense_date"]); $message = $this->FamilyExpense->addFamilyExpense($data); } else if($data["isAdd"] == "9"){ $data["expense_date_old"] = $this->getStrToIntDate($data["expense_date"]); $message = $this->FamilyExpense->modifyFamilyExpense($data); } else if($data["isAdd"] == "10"){ $message = $this->FamilyExpense->deleteFamilyExpense($data); } } if(empty($message)){ echo Configure::read('expensecount.form.validation.success'); } else { $errorMsg = ""; foreach($message as $key=>$value){ $errorMsg .= $key.Configure::read('expensecount.form.validation.pipe').$value.Configure::read('expensecount.form.validation.separator'); } echo $errorMsg; } exit; } exit; } public function displayLog(){ if($this->request->is('ajax')){ $data = array(); $data["expense_id"] = $this->data["Expense"]["logExpenseId"]; $data["fromDate"] = $this->data["Expense"]["fromDate"]; $data["toDate"] = $this->data["Expense"]["toDate"]; // $data["expense_id"] = 14; $dbData = $this->GroupExpense->getGroupExpenseLog($data); echo json_encode($dbData); } exit; } function changeParticipant(){ if($this->request->is('ajax')){ $data = array(); $data["id"] = $this->data["id"]; $data["expense_id"] = $this->data["expense_id"]; $data["name"] = $this->data["name"]; $data["isAdd"] = $this->data["isAdd"]; /* $fp = fopen("Test.txt","a+"); fwrite($fp,mb_strlen($data["name"], 'UTF-8'));exit; */ if($data["isAdd"] == "1"){ $message = $this->Participant->addParticipant($data); } else if($data["isAdd"] == "2") { $message = $this->Participant->modifyParticipant($data); } else if($data["isAdd"] == "3") { $message = $this->Participant->deleteParticpant($data); } if(empty($message)){ echo Configure::read('expensecount.form.validation.success'); } else { $errorMsg = ""; foreach($message as $key=>$value){ $errorMsg .= $key.Configure::read('expensecount.form.validation.pipe').$value.Configure::read('expensecount.form.validation.separator'); } echo $errorMsg; } exit; } exit; } function loadGroupExpense() { $this->render('group_expenses'); } function loadMessExpense() { $this->render('mess_expenses'); } function loadFamilyExpense() { $this->render('family_expenses'); } function loadGroupExpenseDemo() { $this->render('group_expenses_demo'); } function loadMessExpenseDemo() { $this->render('mess_expenses_demo'); } function loadFamilyExpenseDemo() { $this->render('family_expenses_demo'); } function compareOrder($a, $b) { return $a['expenseDate'] - $b['expenseDate']; } function printExpense(){ $expenseArray = json_decode($this->data["Expense"]["printExpense"],true); // pr($this->data);die; $current_perticipants = (isset($this->data["Expense"]["current_perticipants"])) ? $this->data["Expense"]["current_perticipants"] :''; $this->set("requestData",$this->data); $this->set("current_perticipants",$current_perticipants); if(!isset($expenseArray) || empty($expenseArray)){ if ($this->Session->check('cache_page_link')){ $cache_page_link = $this->Session->write("cache_page_link"); $this->Session->delete("cache_page_link"); $this->redirect(array('controller'=> $cache_page_link)); } else { $this->redirect(array('controller'=> "")); } } else { $this->Session->write("cache_page_link",$expenseArray["unique_url"]); } $expenseType = substr($expenseArray["unique_url"], 0, 1); $expenseList = json_decode($this->data["Expense"]["printExpenseList"],true); $this->set("expenseList",$expenseList); // pr($expenseList); $this->set("expense",$expenseArray); $printNames = json_decode($this->data["Expense"]["printNames"],true); $printNamesArray = explode(",",$printNames); $this->layout = 'print'; // $this->Session->read("Config.language"); if($expenseType == "1" || $expenseType == "6" || $expenseType == "2" || $expenseType == "7"){ // echo $this->data["Expense"]["printBalance"];exit; /*if($expenseType == "1" || $expenseType == "2"){ $data = $this->Expense->getGroupExpenseInfoByURL($expenseArray["unique_url"]); } else if($expenseType == "6" || $expenseType == "7"){ $demoData = $this->DemoExpense->getDemoGroupExpenseInfoByURL($expenseArray["unique_url"]); $data['Participant'] = $demoData['DemoParticipant']; $data['GroupExpense'] = $demoData['DemoGroupExpense']; $data['Expense'] = $demoData['DemoExpense']; unset($demoData['DemoParticipant']); unset($demoData['DemoGroupExpense']); unset($demoData['DemoExpense']); } // pr($data['GroupExpense']); if(!empty($data['Participant'])){ foreach ($data['Participant'] as $key => $perticipant) { unset($data['Participant'][$key]); $data['Participant'][$perticipant['participant_id']] = $perticipant; $data['Participant'][$perticipant['participant_id']]['total_charge'] = 0; $data['Participant'][$perticipant['participant_id']]['total_paid'] = 0; $data['Participant'][$perticipant['participant_id']]['currency'] = $data['Expense']['currency']; $perticipants[$perticipant['participant_id']] = $perticipant['name']; } } $this->set("perticipants",$perticipants); if(!empty($data['GroupExpense'])){ $expCounter = 1; foreach ($data['GroupExpense'] as $keya => $groupExpense) { $aa = array(); $aa = explode(',', $groupExpense['participant_amount']); foreach ($aa as $keyb => $vala) { $bb = array(); $bb = explode('|', $vala); $data['Participant'][$bb[0]]['total_charge'] += $bb[2]; } $data['Participant'][$groupExpense['paid_by_participant_id']]['total_paid'] += $groupExpense['amount']; $data['GroupExpense'][$keya]['involve_list'] = $this->getInvolves($data, $groupExpense['participant_amount']); foreach ($data['Participant'] as $participant) { if ($participant['participant_id'] == $groupExpense['paid_by_participant_id']) { $data['GroupExpense'][$keya]['participent_name'] = $participant['name']; } } } } if($current_perticipants != ''){ $tempGroupExpense = $data['GroupExpense']; if(!empty($tempGroupExpense)){ foreach ($tempGroupExpense as $keya => $groupExpense) { if( $groupExpense['paid_by_participant_id'] == $current_perticipants || strpos($groupExpense['participant_amount'], $current_perticipants.'|') !== false ) { // echo 'Yes'; } elseif($current_perticipants != '') { unset($data['GroupExpense'][$keya]); // echo 'NO'; } } } } $this->set("allGroupExpense",$data['GroupExpense']); $this->set("allParticipant",$data['Participant']); $pieDataFinal = array(); if($data['Participant']){ $counter = 0; foreach ($data['Participant'] as $key => $val) { // if( (($current_perticipants != '') && ($val['participant_id'] == $current_perticipants)) || ($current_perticipants == '') ) { $pieDataFinal[$counter]['name'] = $val['name']; $pieDataFinal[$counter]['y'] = $val['total_charge']; $counter++; // } } } $this->set("pieChartDataFinal",json_encode($pieDataFinal));*/ $this->set("printedBy",$printNamesArray[0]); $this->set("createdBy",$printNamesArray[1]); $this->set("createdDate",$printNamesArray[2]); $balanceArray = explode(",",json_decode($this->data["Expense"]["printBalance"],true)); $this->set("balanceArray",$balanceArray); } else if($expenseType == "3" || $expenseType == "8"){ $this->set("createdDate",$printNamesArray[0]); $this->set("totalIncome",$printNamesArray[1]); $this->set("totalExpense",$printNamesArray[2]); $this->set("balance",$printNamesArray[3]); } if($expenseType == "1" || $expenseType == "6"){ $this->render('print'); } else if($expenseType == "2" || $expenseType == "7"){ $parintOption = json_decode($this->data["Expense"]["printOption"],true); if($parintOption == "2" ){ $this->render('meal'); } else if($parintOption == "3" ){ $this->render('my_meal'); }else { $this->render('print_mess'); } } else if($expenseType == "3" || $expenseType == "8"){ $incomeList = json_decode($this->data["Expense"]["printIncomeList"],true); $this->set("incomeList",$incomeList); if($expenseType == "3") { $data = $this->Expense->getFamilyExpenseInfoByURL($expenseArray["unique_url"]); if(!empty($data)){ $fcounter = 0; $temp_total_income = 0; $temp_total_expense = 0; $total_income_str = ''; $total_balance_str = ''; $total_expense_str = ''; foreach ($data['FamilyExpense'] as $key => $familyExpense) { if(!isset($newData[$fcounter]['total_income'])){ $newData[$fcounter]['total_income'] = 0; } if(!isset($newData[$fcounter]['total_expense'])){ $newData[$fcounter]['total_expense'] = 0; } $newData[$fcounter]['expense_date'] = $familyExpense['expense_date']; if($familyExpense['record_type'] == 1) { $temp_total_expense += $familyExpense['amount']; $newData[$fcounter]['expense'] = $familyExpense['amount']; $newData[$fcounter]['income'] = 0; $newData[$fcounter]['total_expense'] = $temp_total_expense; $newData[$fcounter]['total_income'] = $temp_total_income; } elseif($familyExpense['record_type'] == 2) { $temp_total_income += $familyExpense['amount']; $newData[$fcounter]['expense'] = 0; $newData[$fcounter]['income'] = $familyExpense['amount']; $newData[$fcounter]['total_income'] = $temp_total_income; $newData[$fcounter]['total_expense'] = $temp_total_expense; } $newData[$fcounter]['balance'] = $temp_total_income - $temp_total_expense; $newData[$fcounter]['record_type'] = $familyExpense['record_type']; $total_income_str[] = $newData[$fcounter]['total_income']; $total_expense_str[] = $newData[$fcounter]['total_expense']; $total_balance_str[] = $newData[$fcounter]['balance']; $fcounter++; } } $total_income_str = implode(',', $total_income_str); $total_expense_str = implode(',', $total_expense_str); $total_balance_str = implode(',', $total_balance_str); $this->set('total_income_str', $total_income_str); $this->set('total_expense_str', $total_expense_str); $this->set('total_balance_str', $total_balance_str); } $this->render('print_family'); } } public function printReport($uniqueURL=null) { $this->layout = 'print'; if(isset($uniqueURL) && $uniqueURL != "" && $this->request->is('get')){ $expenseType = trim(substr($uniqueURL, 0, 1)); if ($expenseType == "1" || $expenseType == "2") { $data = $this->Expense->getGroupExpenseInfoByURL($uniqueURL); // added by Bijoy $current_perticipants = ''; if(!empty($data['Participant'])){ foreach ($data['Participant'] as $key => $perticipant) { // unset($data['Participant'][$key]); $newdata['Participant'][$perticipant['participant_id']] = $perticipant; $newdata['Participant'][$perticipant['participant_id']]['total_charge'] = 0; $newdata['Participant'][$perticipant['participant_id']]['total_paid'] = 0; $newdata['Participant'][$perticipant['participant_id']]['currency'] = $data['Expense']['currency']; $perticipants[$perticipant['participant_id']] = $perticipant['name']; } } $this->set("perticipants",$perticipants); if ($expenseType == "1" ) { if(!empty($data['GroupExpense'])){ $expCounter = 1; foreach ($data['GroupExpense'] as $keya => $groupExpense) { $aa = array(); $aa = explode(',', $groupExpense['participant_amount']); foreach ($aa as $keyb => $vala) { $bb = array(); $bb = explode('|', $vala); $newdata['Participant'][$bb[0]]['total_charge'] += $bb[2]; } $newdata['Participant'][$groupExpense['paid_by_participant_id']]['total_paid'] += $groupExpense['amount']; $data['GroupExpense'][$keya]['involve_list'] = $this->getInvolves($data, $groupExpense['participant_amount']); foreach ($newdata['Participant'] as $participant) { if ($participant['participant_id'] == $groupExpense['paid_by_participant_id']) { $data['GroupExpense'][$keya]['participent_name'] = $participant['name']; } } } } if($current_perticipants != ''){ $tempGroupExpense = $data['GroupExpense']; if(!empty($tempGroupExpense)){ foreach ($tempGroupExpense as $keya => $groupExpense) { if( $groupExpense['paid_by_participant_id'] == $current_perticipants || strpos($groupExpense['participant_amount'], $current_perticipants.'|') !== false ) { // echo 'Yes'; } elseif($current_perticipants != '') { unset($data['GroupExpense'][$keya]); // echo 'NO'; } } } } $hasMeal = 1; } if ($expenseType == "2" ) { if(!empty($data['GroupExpense'])){ $total_expense = 0; foreach ($data['GroupExpense'] as $keya => $groupExpense) { $total_expense = $total_expense + $groupExpense["amount"]; $newdata['Participant'][$groupExpense['paid_by_participant_id']]['total_paid'] += $groupExpense['amount']; } } $total_meal = 0; $tempParticipantMeal = array(); foreach ($data['Meal'] as $value) { $meal_participants = explode(',', $value['meal_amount']); foreach ($meal_participants as $meal_participant) { $meal_amounts = explode('|', $meal_participant); if(!isset($tempParticipantMeal[$meal_amounts[0]]['meal'])){ $tempParticipantMeal[$meal_amounts[0]]['meal'] = 0; } $tempParticipantMeal[$meal_amounts[0]]['meal'] += $meal_amounts[1] + $meal_amounts[2] + $meal_amounts[3]; $total_meal += $meal_amounts[1] + $meal_amounts[2] + $meal_amounts[3]; } } if(!empty($newdata['Participant'])){ if($total_meal != 0) $meal_rate = $total_expense / $total_meal; foreach ($newdata['Participant'] as $key => $value) { if(isset($tempParticipantMeal[$key])){ $newdata['Participant'][$key]["total_charge"] = $tempParticipantMeal[$key]['meal'] * $meal_rate; } } } $hasMeal = 2; } $this->set("hasMeal",$hasMeal); $this->set("current_perticipants",$current_perticipants); $this->set("allGroupExpense",$data['GroupExpense']); $this->set("allParticipant",$newdata['Participant']); $pieDataFinal = array(); if($newdata['Participant']){ $counter = 0; foreach ($newdata['Participant'] as $key => $val) { // if( (($current_perticipants != '') && ($val['participant_id'] == $current_perticipants)) || ($current_perticipants == '') ) { $pieDataFinal[$counter]['name'] = $val['name']; $pieDataFinal[$counter]['y'] = $val['total_charge']; $counter++; // } } } $this->set("pieChartDataFinal",json_encode($pieDataFinal)); } elseif($expenseType == "3") { $current_perticipants = ''; $data = $this->Expense->getFamilyExpenseInfoByURL($uniqueURL); if(!empty($data)){ $data["Category"] = $this->getCategories(); } $total_family_income = 0; $total_family_expense = 0; if(!empty($data['FamilyExpense']) && isset($data['FamilyExpense'])){ foreach ($data['FamilyExpense'] as $family_expense) { if($family_expense['record_type'] == 1){ $total_family_expense = $total_family_expense + $family_expense['amount']; } elseif ($family_expense['record_type'] == 2) { $total_family_income = $total_family_income + $family_expense['amount']; } } } $this->set('total_family_income', $total_family_income); $this->set('total_family_expense', $total_family_expense); $this->set('data', $data); if(!empty($data)){ $fcounter = 0; $temp_total_income = 0; $temp_total_expense = 0; $total_income_str = ''; $total_balance_str = ''; $total_expense_str = ''; foreach ($data['FamilyExpense'] as $key => $familyExpense) { if(!isset($newData[$fcounter]['total_income'])){ $newData[$fcounter]['total_income'] = 0; } if(!isset($newData[$fcounter]['total_expense'])){ $newData[$fcounter]['total_expense'] = 0; } $newData[$fcounter]['expense_date'] = $familyExpense['expense_date']; if($familyExpense['record_type'] == 1) { $temp_total_expense += $familyExpense['amount']; $newData[$fcounter]['expense'] = $familyExpense['amount']; $newData[$fcounter]['income'] = 0; $newData[$fcounter]['total_expense'] = $temp_total_expense; $newData[$fcounter]['total_income'] = $temp_total_income; } elseif($familyExpense['record_type'] == 2) { $temp_total_income += $familyExpense['amount']; $newData[$fcounter]['expense'] = 0; $newData[$fcounter]['income'] = $familyExpense['amount']; $newData[$fcounter]['total_income'] = $temp_total_income; $newData[$fcounter]['total_expense'] = $temp_total_expense; } $newData[$fcounter]['balance'] = $temp_total_income - $temp_total_expense; $newData[$fcounter]['record_type'] = $familyExpense['record_type']; $total_income_str[] = $newData[$fcounter]['total_income']; $total_expense_str[] = $newData[$fcounter]['total_expense']; $total_balance_str[] = $newData[$fcounter]['balance']; $fcounter++; } } // pr($newData); $total_income_str = implode(',', $total_income_str); $total_expense_str = implode(',', $total_expense_str); $total_balance_str = implode(',', $total_balance_str); $this->set('total_income_str', $total_income_str); $this->set('total_expense_str', $total_expense_str); $this->set('total_balance_str', $total_balance_str); $this->set("current_perticipants",$current_perticipants); $this->render('print_family_report'); } if(!empty($data['GroupExpense']) && isset($data['GroupExpense'])) { foreach ($data['GroupExpense'] as $key => $groupExpense) { $data['GroupExpense'][$key]['involve_list'] = $this->getInvolves($data, $groupExpense['participant_amount']); foreach ($data['Participant'] as $participant) { if ($participant['participant_id'] == $groupExpense['paid_by_participant_id']) { $data['GroupExpense'][$key]['participent_name'] = $participant['name']; }; } } } if(!empty($data)){ $this->set('data', $data); /*echo "
";
                // print_r($data);exit;*/

            }
        } elseif($this->request->is('Post')) {

            $uniqueURL = $this->request->data('unique_url');
            $expenseType = trim(substr($uniqueURL, 0, 1));

            if ($expenseType == "1" || $expenseType == "2") {
                $data = $this->Expense->getGroupExpenseInfoByURL($uniqueURL);

                // added by Bijoy
                if(isset($this->request->data['participant_id']) && !empty($this->request->data('participant_id'))){
	                $current_perticipants = $this->request->data('participant_id');
	            } else {
	            	$current_perticipants = '';
	            }
                if(!empty($data['Participant'])){
					foreach ($data['Participant'] as $key => $perticipant) {
						// unset($data['Participant'][$key]);
						$newdata['Participant'][$perticipant['participant_id']] = $perticipant;
						$newdata['Participant'][$perticipant['participant_id']]['total_charge'] = 0;
						$newdata['Participant'][$perticipant['participant_id']]['total_paid'] = 0;
						$newdata['Participant'][$perticipant['participant_id']]['currency'] = $data['Expense']['currency'];

						$perticipants[$perticipant['participant_id']] = $perticipant['name'];
					}
				}
				$this->set("perticipants",$perticipants);

                if ($expenseType == "1" ) {
					if(!empty($data['GroupExpense'])){ $expCounter = 1;
						foreach ($data['GroupExpense'] as $keya => $groupExpense) {
							$aa = array();
							$aa = explode(',', $groupExpense['participant_amount']);
							foreach ($aa as $keyb => $vala) {
								$bb = array();
								$bb = explode('|', $vala);
								$newdata['Participant'][$bb[0]]['total_charge'] += $bb[2];
							}
							$newdata['Participant'][$groupExpense['paid_by_participant_id']]['total_paid'] += $groupExpense['amount'];

							$data['GroupExpense'][$keya]['involve_list'] = $this->getInvolves($data, $groupExpense['participant_amount']);

		                    foreach ($newdata['Participant'] as $participant) {
		                        if ($participant['participant_id'] == $groupExpense['paid_by_participant_id']) {
		                            $data['GroupExpense'][$keya]['participent_name'] = $participant['name'];
		                        }
		                    }
						}
					}
					if($current_perticipants != ''){
						$tempGroupExpense = $data['GroupExpense'];
						if(!empty($tempGroupExpense)){
							foreach ($tempGroupExpense as $keya => $groupExpense) {
								if( $groupExpense['paid_by_participant_id'] == $current_perticipants || strpos($groupExpense['participant_amount'], $current_perticipants.'|') !== false ) {
									// echo 'Yes';
								} elseif($current_perticipants != '') {
									unset($data['GroupExpense'][$keya]);
									// echo 'NO';
								}
							}
						}
					}
					$hasMeal = 1;
				}
				if ($expenseType == "2" ) {
					if(!empty($data['GroupExpense'])){ $total_expense = 0;
						foreach ($data['GroupExpense'] as $keya => $groupExpense) {
							$total_expense = $total_expense + $groupExpense["amount"];
							$newdata['Participant'][$groupExpense['paid_by_participant_id']]['total_paid'] += $groupExpense['amount'];
						}
					}


					$total_meal = 0; $tempParticipantMeal = array();
		            foreach ($data['Meal'] as $value) {
		                $meal_participants = explode(',', $value['meal_amount']);
		                foreach ($meal_participants as $meal_participant) {
		                    $meal_amounts = explode('|', $meal_participant);
		                    if(!isset($tempParticipantMeal[$meal_amounts[0]]['meal'])){
		                        $tempParticipantMeal[$meal_amounts[0]]['meal'] = 0;
		                    }
		                    $tempParticipantMeal[$meal_amounts[0]]['meal'] += $meal_amounts[1] + $meal_amounts[2] + $meal_amounts[3];
		                    $total_meal += $meal_amounts[1] + $meal_amounts[2] + $meal_amounts[3];
		                }
		            }
		            if(!empty($newdata['Participant'])){
		            	if($total_meal != 0)
				            $meal_rate = $total_expense / $total_meal;
		            	foreach ($newdata['Participant'] as $key => $value) {
		            		if(isset($tempParticipantMeal[$key])){
				                $newdata['Participant'][$key]["total_charge"] = $tempParticipantMeal[$key]['meal'] * $meal_rate;
		            		}
		            	}
		            }
		            $hasMeal = 2;
				}
				$this->set("hasMeal",$hasMeal);
				$this->set("current_perticipants",$current_perticipants);
				$this->set("allGroupExpense",$data['GroupExpense']);
				$this->set("allParticipant",$newdata['Participant']);
				$pieDataFinal = array();
				if($newdata['Participant']){ $counter = 0;
				 	foreach ($newdata['Participant'] as $key => $val) {
				 		// if( (($current_perticipants != '') && ($val['participant_id'] == $current_perticipants)) || ($current_perticipants == '') ) {
					 		$pieDataFinal[$counter]['name'] = $val['name'];
					 		$pieDataFinal[$counter]['y'] = $val['total_charge'];
					 		$counter++;
				 		// }
				 	}
				}
				$this->set("pieChartDataFinal",json_encode($pieDataFinal));

            } elseif($expenseType == "3") {
            	// added by Bijoy
            	// pr($this->request->data);
                if(isset($this->request->data['current_perticipants']) && !empty($this->request->data['current_perticipants'])){
	                $current_perticipants = $this->request->data['current_perticipants'];
	            } else {
	            	$current_perticipants = '';
	            }
                $data = $this->Expense->getFamilyExpenseInfoByURL($uniqueURL);
                if(!empty($data)){
                    $data["Category"] =  $this->getCategories();
                }
                $total_family_income = 0;
                $total_family_expense = 0;
                if(!empty($data['FamilyExpense']) && isset($data['FamilyExpense'])){
                    foreach ($data['FamilyExpense'] as $family_expense) {
                        if($family_expense['record_type'] == 1){
                            $total_family_expense = $total_family_expense + $family_expense['amount'];
                        } elseif ($family_expense['record_type'] == 2) {
                            $total_family_income = $total_family_income + $family_expense['amount'];
                        }
                    }
                }
                $this->set('total_family_income', $total_family_income);
                $this->set('total_family_expense', $total_family_expense);
                $this->set('data', $data);


				if(!empty($data)){ 
					$fcounter = 0;
					$temp_total_income = 0;
					$temp_total_expense = 0;
					$total_income_str = '';
					$total_balance_str = '';
					$total_expense_str = '';
					foreach ($data['FamilyExpense'] as $key => $familyExpense) {
						if(!isset($newData[$fcounter]['total_income'])){
							$newData[$fcounter]['total_income'] = 0;
						}
						if(!isset($newData[$fcounter]['total_expense'])){
							$newData[$fcounter]['total_expense'] = 0;
						}
						$newData[$fcounter]['expense_date'] = $familyExpense['expense_date'];

						if($familyExpense['record_type'] == 1)
						{
							$temp_total_expense += $familyExpense['amount'];
							$newData[$fcounter]['expense'] = $familyExpense['amount'];
							$newData[$fcounter]['income'] = 0;
							$newData[$fcounter]['total_expense'] = $temp_total_expense;
							$newData[$fcounter]['total_income'] = $temp_total_income;
						} 
						elseif($familyExpense['record_type'] == 2)
						{
							$temp_total_income += $familyExpense['amount'];
							$newData[$fcounter]['expense'] = 0;
							$newData[$fcounter]['income'] = $familyExpense['amount'];
							$newData[$fcounter]['total_income'] = $temp_total_income;
							$newData[$fcounter]['total_expense'] = $temp_total_expense;
						}

							$newData[$fcounter]['balance'] = $temp_total_income - $temp_total_expense;

						$newData[$fcounter]['record_type'] = $familyExpense['record_type'];
						$total_income_str[] = $newData[$fcounter]['total_income'];
						$total_expense_str[] = $newData[$fcounter]['total_expense'];
						$total_balance_str[] = $newData[$fcounter]['balance'];
						$fcounter++;
					}
				}
				// pr($newData);
				$total_income_str = implode(',', $total_income_str);
				$total_expense_str = implode(',', $total_expense_str);
				$total_balance_str = implode(',', $total_balance_str);
				$this->set('total_income_str', $total_income_str);
                $this->set('total_expense_str', $total_expense_str);
                $this->set('total_balance_str', $total_balance_str);
				$this->set("current_perticipants", $current_perticipants);


                $this->render('print_family_report');
            }
            if(isset($this->request->data['participant_id']) && !empty($this->request->data('participant_id'))){
                $participant_id = $this->request->data('participant_id');
                if($expenseType == "1") {
                	$data = $this->filterExpenseData($participant_id, $data);
                }
                $this->set('participant_id', $participant_id);
            }
            if(!empty($data['GroupExpense'])){
	            foreach ($data['GroupExpense'] as $key => $groupExpense) {
	                $data['GroupExpense'][$key]['involve_list'] = $this->getInvolves($data, $groupExpense['participant_amount']);

	                foreach ($data['Participant'] as $participant) {
	                    if($participant['participant_id'] == $groupExpense['paid_by_participant_id']){
	                        $data['GroupExpense'][$key]['participent_name'] = $participant['name'];
	                    };
	                }
	            }
            }
            if(!empty($data)){
                $this->set('data', $data);

            }
        }
    }

    private function getInvolves($data, $involves)
    {
        $involveStrAll =[];
        $involveStrExcept = "";
        $involvesArray = explode(',', $involves);
        foreach ($involvesArray as $involve)
        {
            $involve_id = explode('|', $involve);
            foreach($data['Participant'] as $participant){
               if($participant['participant_id'] == $involve_id[0]) {
                    $involveStrAll[] = $participant['name'];
                }
            }
        }
        if(count($involveStrAll) == count($data['Participant'])){
            $involveStrExcept = "all";
        } else {
            foreach($data['Participant'] as $participant) {
                if(!in_array($participant['name'], $involveStrAll)) {
                    if($involveStrExcept == "") {
                        $involveStrExcept = "All except ".$participant['name'];
                    } else {
                        $involveStrExcept .= ", ".$participant['name'];
                    }
                }
            }
        }
        $involveStrAll = implode(', ', $involveStrAll);
        if(strlen($involveStrExcept) > strlen($involveStrAll)) {
            $involveStrExcept = $involveStrAll;
        }
       return $involveStrExcept;
    }

    private function filterExpenseData($participant_id, $data)
    {

        $tempGroupExpense = $data['GroupExpense'];

        foreach ($tempGroupExpense as $key => $groupExpense){
            $participanyArray = [];
            $involvesArray = explode(',', $groupExpense['participant_amount']);
            foreach ($involvesArray as $involve)
            {
                $involve_id = explode('|', $involve);
                $participanyArray[] = $involve_id[0];
                if($involve_id[0] == $participant_id) {
                    $data['GroupExpense'][$key]['my_expense'] =  $involve_id[2];
                }
            }
            if(!in_array($participant_id, $participanyArray)){

                unset($data['GroupExpense'][$key]);
            }
        }
        /*echo "
";
        print_r($data);exit;*/

        return $data;
    }

    public function generatePdf()
    {
        $html = $this->request->data['whole_content'];
        // pr($html); die;
        $mpdf = new mPDF();
        $mpdf->SetProtection(array("print"));
        $stylesheet = file_get_contents(CDN_URL.'css/print_report.css');
        $mpdf->WriteHTML($stylesheet,1);
        $mpdf->WriteHTML($html, 2);
        $rand = rand(1000, 10000);
        $reportUrl = "reports/";
        if(!is_dir($reportUrl)){
            mkdir($reportUrl,0777,true);
        }
        $filename = $reportUrl.$rand."_".time()."_"."expenses.pdf";
        // echo $html; die;
        $mpdf->Output($filename);

        if (file_exists($filename)) {
            header('Content-type: application/pdf');
            header('Content-Disposition: attachment; filename='.$filename);
            readfile($filename);
            @unlink($filename);
            exit;
        }
    }

    public function generateCSV()
    {
        $data = $this->request->data['csv_content'];
        $data_summary = $this->request->data['csv_summary_content'];
        $data_meal = $this->request->data['csv_meal_content'];
        $hasMeal = $this->request->data['hasMeal'];

        $adata = unserialize($data);
        $adata_summary = unserialize($data_summary);
        $adata_meal = unserialize($data_meal);
        // echo "
";        print_r($adata_meal);exit;
        $rand = rand(1000, 10000);
        $filename = $rand.'_'.time().'_expense.csv';
        ob_start();
        header('Content-Encoding: UTF-8');
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        $fp = fopen('php://output', 'w');

        if(!empty($adata)){
            fputcsv($fp, ['', 'All Expenses', '','','','']);
            if($adata[0]['my_expense']>0)
       			fputcsv($fp, ['Who Paid?', 'How Much?', 'For what reasons?', 'When', 'Involves', 'My Expense']);
       		else
       			fputcsv($fp, ['Who Paid?', 'How Much?', 'For what reasons?', 'When', 'Involves', '']);

            $totalAmount = 0;
            $my_expenseAmount = 0;
	        foreach ($adata as $data) {
	        	$totalAmount += $data['amount'];
	        	$my_expenseAmount += $data['my_expense'];
	            $transaction_row = array();
	            if (!empty($data)) {
	                $transaction_row = [
	                    $data['participent_name'],
	                    $data['amount'] . " " . $data['currency'],
	                    $data['what'],
	                    $data['expense_date_new'],
	                    $data['involve_list'],
	                    ($data['my_expense']>0) ? $data['my_expense'] . " " . $data['currency']:''
	                ];
	            }
	            fputcsv($fp, $transaction_row);
	        }
	        if($my_expenseAmount > 0)
	            fputcsv($fp, ['Total:', $totalAmount . " " . $data["currency"], '','','Total',$my_expenseAmount . " " . $data["currency"]]);
	        else
	            fputcsv($fp, ['Total:', $totalAmount . " " . $data["currency"], '','','','']);
            fputcsv($fp, ['', '', '','','','']);
        } else {
        	fputcsv($fp, ['', 'All Expenses', '','','','']);
       		fputcsv($fp, ['Who Paid?', 'How Much?', 'For what reasons?', 'When', 'Involves', '']);
       		fputcsv($fp, ['No Data Available in table', '', '', '', '', '']);
       		fputcsv($fp, ['', '', '','','','']);
        }

        if($hasMeal == 2){
	        if(!empty($adata_meal)){
	            fputcsv($fp, ['','Meal','','','','']);					
	       		fputcsv($fp, ['Date', 'Day', 'Breakfast', 'Lunch', 'Dinner', 'Total']);

	            $total = 0;
		        foreach ($adata_meal as $data) {
		        	$total += $data['subtotal'];
		            $transaction_row = array();
		            if (!empty($data)) {
		                $transaction_row = [
		                    $data['create_date'],
		                    $data['day'],
		                    $data['breakfast'],
		                    $data['lunch'],
		                    $data['dinner'],
		                    $data['subtotal']
		                ];
		            }
		            fputcsv($fp, $transaction_row);
		        }

	            fputcsv($fp, ['','','','','Total:',$total]);
	            fputcsv($fp, ['','','','','','']);
	        } else {
	        	fputcsv($fp, ['','Meal','','','','']);					
	       		fputcsv($fp, ['Date', 'Day', 'Breakfast', 'Lunch', 'Dinner', 'Total']);
	       		fputcsv($fp, ['No meal available', '', '', '', '', '']);
	       		fputcsv($fp, ['', '', '','','','']);
	        }
        }

        if(!empty($adata_summary)){
            fputcsv($fp, ['', 'Summary Report', '','','','']);
            fputcsv($fp, ['Participants', 'Charged', 'Paid', 'Due']);

	        foreach ($adata_summary as $data) {
	            $transaction_row = array();
	            if (!empty($data)) {
	                $transaction_row = [
	                    $data['name'],
	                    $data['total_charge'] . " " . $data['currency'],
	                    $data['total_paid'] . " " . $data['currency'],
	                    $data['due'] . " " . $data['currency']
	                ];
	            }
	            fputcsv($fp, $transaction_row);
	        }

        }
        fclose($fp);
        exit;
    }

    public function generateFamilyCSV()
    {
        $csv_expense_heading = $this->request->data['csv_expense_heading'];
        $csv_income_heading = $this->request->data['csv_income_heading'];
        $income_data = $this->request->data['csv_income_content'];
        $expense_data = $this->request->data['csv_expense_content'];

        $aincome_data = unserialize($income_data);
        $aexpense_data = unserialize($expense_data);
        $aexpense_heading = unserialize($csv_expense_heading);
        $aincome_heading = unserialize($csv_income_heading);
        // echo "
";        print_r($aexpense_heading);
        // echo "
";        print_r($aexpense_data);
        // echo "
";        print_r($aincome_heading);
        // echo "
";        print_r($aincome_data);
        // exit;
        $rand = rand(1000, 10000);
        $filename = $rand.'_'.time().'_expense.csv';
        ob_start();
        header('Content-Encoding: UTF-8');
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        $fp = fopen('php://output', 'w');

        if(!empty($aincome_data)){
            fputcsv($fp, ['', 'All Incomes', '','']);
       		fputcsv($fp, [$aincome_heading['nameHeading'], $aincome_heading['categoryHeading'], $aincome_heading['dateHeading'],$aincome_heading['amountHeading']]);

            $totalAmount = 0;
	        foreach ($aincome_data as $data) {
	        	$totalAmount += $data['amount'];
	            $transaction_row = array();
	            if (!empty($data)) {
	                $transaction_row = [
	                    $data['expenseName'],
	                    $data['expenseCategory'],
	                    $data['expenseDate'],
	                    $data['amount'] . " " . $data['currency'],
	                ];
	            }
	            fputcsv($fp, $transaction_row);
	        }
	            fputcsv($fp, ['','','Total:', $totalAmount . " " . $data["currency"]]);
            fputcsv($fp, ['', '', '', '']);
        }
        if(!empty($aexpense_data)){
            fputcsv($fp, ['', 'All Expenses', '','']);
       		fputcsv($fp, [$aexpense_heading['nameHeading'], $aexpense_heading['categoryHeading'], $aexpense_heading['dateHeading'],$aexpense_heading['amountHeading']]);

            $totalAmount = 0;
	        foreach ($aexpense_data as $data) {
	        	$totalAmount += $data['amount'];
	            $transaction_row = array();
	            if (!empty($data)) {
	                $transaction_row = [
	                    $data['expenseName'],
	                    $data['expenseCategory'],
	                    $data['expenseDate'],
	                    $data['amount'] . " " . $data['currency'],
	                ];
	            }
	            fputcsv($fp, $transaction_row);
	        }
	            fputcsv($fp, ['','','Total:', $totalAmount . " " . $data["currency"]]);
            fputcsv($fp, ['', '', '', '']);
        }


        fclose($fp);
        exit;
    }
	 
}
?>