/**
  * Build records that will be used in rendering the reports
  * @param int $prop_id ID used to identify the property
  * @param string $start Date string specifying start of the period
  * @param sring $end Date string specifyinng end of the period
  * @return array $record_objects An array of record objects
  */
 public static function buildRecords($prop_id, $start, $end)
 {
     $room_count = Room::getNumRoomsForProperty($prop_id);
     $rooms = Room::findByPropertyId($prop_id);
     $record_objects = array();
     $aobj = new Arrears();
     for ($i = 0; $i < $room_count; $i++) {
         $record = new self();
         $rm = $rooms[$i];
         $record->room_label = $rm->getRoomLabel();
         if (!is_null($rm->getTenantId())) {
             $tenant = Tenant::findByRoomId($rm->id);
             $rent_obj = Rent::findByPeriodForTenant($tenant->id, $start, $end);
             $rent_paid = !is_null($rent_obj) ? $rent_obj->getPaymentAmount() : NULL;
             $receipt = !is_null($rent_obj) ? $rent_obj->getReceiptNo() : NULL;
             $remarks = !is_null($rent_obj) ? $rent_obj->getRemarks() : NULL;
             $arrears_paid = ArrearsPaid::calcAmountPaidByTenantDuringPeriod($tenant->id, $start, $end);
             $arrears = $aobj->calcTotalArrearsFromTenant($tenant->id);
             $deposit_obj = Deposit::findByPeriodForTenant($tenant->id, $start, $end);
             $deposit_paid = !is_null($deposit_obj) ? $deposit_obj->getPaymentAmount() : NULL;
             $kplc_obj = DepositKPLC::findByPeriodForTenant($tenant->id, $start, $end);
             $kplc_paid = !is_null($kplc_obj) ? $kplc_obj->getPaymentAmount() : NULL;
             $eldowas_obj = DepositEldowas::findByPeriodForTenant($tenant->id, $start, $end);
             $eldowas_paid = !is_null($eldowas_obj) ? $eldowas_obj->getPaymentAmount() : NULL;
             $totals = $tenant->calcPaymentsMadeDuringPeriod($start, $end);
             $record->tenant = $tenant->getFullName();
             $record->receipt_no = $receipt;
             $record->rent_pm = $rm->getRent();
             $record->rent_paid = $rent_paid;
             $record->arrears_paid = $arrears_paid;
             $record->arrears = $arrears;
             $record->house_deposit = $deposit_paid;
             $record->kplc_deposit = $kplc_paid;
             $record->eldowas_deposit = $eldowas_paid;
             $record->totals = $totals;
             $record->remarks = $remarks;
         } else {
             $record->tenant = "VACANT";
             $record->rent_pm = $rm->getRent();
         }
         $record_objects[] = $record;
     }
     return $record_objects;
 }
<?php

require_once '../lib/init.php';
if (!$session->isLoggedIn()) {
    redirect_to('../index.php');
}
if (isset($_GET['submit'])) {
    $type = (int) $_GET['type'];
    $receipt_no = $_GET['receipt'];
    if (empty($receipt_no)) {
        $err = "Enter the receipt number issued for the transaction";
    } else {
        switch ($type) {
            case 1:
                $payment = Rent::findByReceiptNo($receipt_no);
                break;
            case 0:
                $payment = ArrearsPaid::findByReceiptNo($receipt_no);
                break;
        }
    }
}
include_layout_template('admin_header.php');
?>

	<div id="container">
    <h3>Actions</h3>
    <div id="side-bar">
	<?php 
$actions = array("tenants" => "Tenants", "tenant_search" => "Search Tenant", "tenants_old" => "Previous Tenants", "status" => "Payment Status");
echo create_action_links($actions);
    public function parseRents( $rents ) {
                  
       try {
            $client = Client::find(array('phone'=>$rents[7]));
            $inventory = Inventories::find( array('number'=>$rents[3]) );
            $shift = null;
            
            $date = $this->searchDate( $rents[0] );
            
            if(!is_null($date) )
                $shift = Shift::find(array('shiftDate'=>$date));
             
            
            $idInventory = -1;
            $idClient = -1;
            $idShift = -1;
            
            if ( !is_null($inventory) )
                 $idInventory = $inventory->id;
            
            if ( !is_null($client) )
                $idClient = $client->id;
            
            if ( !is_null($shift) ) {
                $idShift = $shift->id;                                        
                //echo $idShift."<br>";
            }
                
            
             Rent::create( array( 'start'=>$rents[1], 
                                    'end'=>$rents[2],
                                    'idInventory'=>$idInventory,
                                    'idClient'=>$idClient,
                                    'expense'=>$rents[22],
                                    'idShift'=>$idShift ) );  
            
        } catch (\exception $e) {
            //echo "Exception in parseRents <br>";
            echo $e->getMessage()."<br>";
        }    

    }
    redirect_to('../index.php');
}
if (!$ac->hasPermission('delete_rent')) {
    $mesg = "You don't have permission to access this page";
    $session->message($mesg);
    redirect_to($_SERVER['HTTP_REFERER']);
}
if (isset($_GET['tid']) && !empty($_GET['tid']) && (isset($_GET['id']) && !empty($_GET['id']))) {
    $tenant_id = (int) $_GET['tid'];
    $payment_id = (int) $_GET['id'];
    if (!is_int($tenant_id) || !is_int($payment_id)) {
        $mesg = "Rent payment could not be deleted. An invalid value was sent through the URL";
        $session->message($mesg);
        redirect_to('tenants.php');
    } else {
        $rent = Rent::findById($payment_id);
        if (is_null($rent)) {
            $mesg = "Rent payment could not be found in the system";
            $session->message($mesg);
            redirect_to("tenant.php?tid={$tenant_id}");
        } else {
            if ($rent->deletePayment()) {
                $mesg = "Rent payment deleted";
                $session->message($mesg);
                redirect_to("tenant.php?tid={$tenant_id}");
            } else {
                $mesg = "An error occured preventing the rent payment from deleted";
                $session->message($mesg);
                redirect_to("tenant.php?tid={$tenant_id}");
            }
        }
 /**
  * Generate a report that outlines the rent collection for a particular 
  * property over a specified period of time
  * @param mixed $title The report title
  * @param object $result_obj A result object obtained from a SELECT query
  * @param object $arrears_paid_obj A result object obtained from a SELECT query
  * @param object $arrears_obj A result object obtained from a SELECT query
  * @param object $expenses_obj A result object obtained from a SELECT query
  * @param array $headings Array of table heading names
  * @param array $widths Array of column widths
  * @param array $aligns Array of column alignments
  * @param string $orientation The page orientation of the report
  * @param mixed $page_size Dimensions of page that displays report
  * @param int $prop_id The ID used to identify the property
  * @param string $start Date string specifying start of the period
  * @param string $end Date string specifying end of the period
  */
 public function pdf($title, $result_obj, $arrears_paid_obj, $arrears_obj, $expenses_obj, $headings = NULL, $widths = NULL, $aligns = NULL, $orientation = 'P', $page_size = 'A4', $prop_id, $start, $end)
 {
     define('HORZ_PADDING', 2);
     define('VERT_PADDING', 3);
     $filename = date('Y-m-d') . '-report-' . uniqid() . '.pdf';
     $pdf = new PDF_Report($orientation, 'pt', $page_size);
     $pdf->set_title($title);
     $pdf->setStartPeriod($start);
     $pdf->setEndPeriod($end);
     $pdf->SetX(-1);
     $page_width = $pdf->GetX() + 1;
     $pdf->AliasNbPages();
     $pdf->SetFont('Helvetica', '', 7);
     $pdf->SetLineWidth(0.1);
     $pdf->SetMargins(self::PDF_MARGIN, self::PDF_MARGIN);
     $pdf->SetAutoPageBreak(true, self::PDF_MARGIN);
     $pdf->SetHorizontalPadding(HORZ_PADDING);
     $pdf->SetVerticalPadding(VERT_PADDING);
     $ncols = $this->columnCount($result_obj);
     // Instantiate Helper Variables
     $rent = new Rent();
     $total_collection = Rent::calcTotalCollection($prop_id, $start, $end);
     $paid_arrears = ArrearsPaid::calcCollectionForPropertyDuringPeriod($prop_id, $start, $end);
     $owed_arrears = Arrears::calcArrearsForPropertyDuringPeriod($prop_id, $start, $end);
     $collection_summary = Rent::calcCollectionSummary($prop_id, $start, $end);
     $mgt_fee = $rent->calcManagementFee($prop_id, $start, $end);
     $net_amount = $rent->calcBalanceAfterMgtFee($prop_id, $start, $end);
     $total_expenses = Expense::calcTotalExpenses($prop_id, $start, $end);
     $net_banking = $rent->calcNetBanking($prop_id, $start, $end);
     $rent_collection_array = array(0 => 'Rent Collection', 1 => $total_collection);
     $paid_arrears_array = array(0 => 'Paid Arrears', 1 => $paid_arrears);
     $summary_collection_array = array(0 => 'Total Collection', 1 => $collection_summary);
     $percentage_mgt_fee = Property::findById($prop_id)->getManagementFee();
     $percentage_mgt_fee = '(' . $percentage_mgt_fee . '%)';
     $mgt_fee_array = array(0 => 'Management Fee' . $percentage_mgt_fee, 1 => $mgt_fee);
     $net_amount_array = array(0 => 'Net Collection (Balance after Management Fee)', 1 => $net_amount);
     $total_expenses_array = array(0 => 'Total Expenses', 1 => $total_expenses);
     $net_banking_array = array(0 => 'Banking(Money Deposited to Landlord\'s Account)', 1 => $net_banking);
     if (is_null($headings)) {
         $headings = $this->columnHeadings($result_obj);
     }
     //$pdf->set_headings($headings);
     //$pdf->SetFont('Helvetica', 'B', 8);
     //$pdf->RowX($headings, false);/
     if (is_null($widths)) {
         $w = ($page_width - 2 * self::PDF_MARGIN) / $ncols;
         for ($i = 0; $i < $ncols; $i++) {
             $widths[$i] = $w;
         }
     }
     if (count($widths) == $ncols - 1) {
         $n = 0;
         foreach ($widths as $w) {
             $n += $w;
         }
         $widths[$ncols - 1] = $page_width - 2 * self::PDF_MARGIN - $n;
     }
     $pdf->SetWidths($widths);
     if (!is_null($aligns)) {
         $a = 'R';
         for ($i = 0; $i < $ncols; $i++) {
             $aligns[$i] = $a;
         }
     }
     $pdf->SetAligns($aligns);
     $pdf->AddPage();
     $pdf->SetFont('Helvetica', 'B', 8);
     $pdf->RowX($headings, false);
     $pdf->SetFont('Helvetica', '', 7);
     while ($row = $result_obj->fetch_row()) {
         $pdf->RowX($row);
     }
     if (!is_null($total_collection)) {
         $xPos = $page_width - (self::PDF_MARGIN + $w);
         $pdf->SetX($xPos);
         $pdf->SetFont('Times', 'B', 8);
         $text = "Total: " . $total_collection;
         $pdf->MultiCell($w, 12, $text, 1, 'R');
     }
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetX(0 + self::PDF_MARGIN);
     $pdf->SetFont('Arial', 'B', 10);
     $pdf->SetTextColor(24);
     $timestamp_start = strtotime($start);
     $timestamp_end = strtotime($end);
     $text_arrears_paid = "Arrears Collected for Period ";
     $text_arrears_paid .= strftime("%B %d, %Y", $timestamp_start);
     $text_arrears_paid .= " to " . strftime("%B %d, %Y", $timestamp_end);
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, $text_arrears_paid, 'B', 'C');
     $pdf->Ln();
     // Arrears Paid
     if ($arrears_paid_obj->num_rows >= 1) {
         $col_count_arrears_paid = $this->columnCount($arrears_paid_obj);
         $arrears_paid_headings = $this->columnHeadings($arrears_paid_obj);
         $arrears_paid_widths = array();
         $w = ($page_width - 2 * self::PDF_MARGIN) / $col_count_arrears_paid;
         for ($i = 0; $i < $col_count_arrears_paid; $i++) {
             $arrears_paid_widths[$i] = $w;
         }
         //$pdf->SetWidths(array(70, 70, 70, 70, 70, 70));
         $pdf->SetWidths($arrears_paid_widths);
         $arrears_paid_aligns = array();
         $a = 'R';
         for ($i = 0; $i < $col_count_arrears_paid; $i++) {
             $arrears_paid_aligns[$i] = $a;
         }
         $pdf->SetAligns($arrears_paid_aligns);
         $pdf->SetFont('Helvetica', 'B', 8);
         $pdf->RowX($arrears_paid_headings, false);
         $pdf->SetFont('Helvetica', '', 7);
         while ($row = $arrears_paid_obj->fetch_row()) {
             $pdf->RowX($row);
         }
         if (!is_null($paid_arrears)) {
             $xPos = $page_width - (self::PDF_MARGIN + $w);
             $pdf->SetX($xPos);
             $pdf->SetFont('Times', 'B', 8);
             $text = "Total: " . $paid_arrears;
             $pdf->MultiCell($w, 12, $text, 1, 'R');
         }
     } else {
         $no_arrears = "Ksh. 0.00";
         $xPos = $page_width - (self::PDF_MARGIN + $w);
         $pdf->SetX($xPos);
         $pdf->MultiCell($w, 8, $no_arrears, 0, 'R');
         $pdf->Ln();
     }
     // Outstanding Arrears
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetX(0 + self::PDF_MARGIN);
     $pdf->SetFont('Arial', 'B', 10);
     $pdf->SetTextColor(24);
     $arrears_owed = "Outstanding Rent Arrears for the Period ";
     $arrears_owed .= strftime("%B %d, %Y", $timestamp_start);
     $arrears_owed .= " to " . strftime("%B %d, %Y", $timestamp_end);
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, $arrears_owed, 'B', 'C');
     $pdf->Ln();
     if ($arrears_obj->num_rows >= 1) {
         $col_count_arrears = $this->columnCount($arrears_obj);
         $arrears_headings = $this->columnHeadings($arrears_obj);
         $arrears_widths = array();
         $w = ($page_width - 2 * self::PDF_MARGIN) / $col_count_arrears;
         for ($i = 0; $i < $col_count_arrears; $i++) {
             $arrears_widths[$i] = $w;
         }
         //$pdf->SetWidths(array(70, 70, 70, 70, 70, 70));
         $pdf->SetWidths($arrears_widths);
         $arrears_aligns = array();
         $a = 'R';
         for ($i = 0; $i < $col_count_arrears; $i++) {
             $arrears_aligns[$i] = $a;
         }
         $pdf->SetAligns($arrears_aligns);
         $pdf->SetFont('Helvetica', 'B', 8);
         $pdf->RowX($arrears_headings, false);
         $pdf->SetFont('Helvetica', '', 7);
         while ($row = $arrears_obj->fetch_row()) {
             $pdf->RowX($row);
         }
         if (!is_null($owed_arrears)) {
             $xPos = $page_width - (self::PDF_MARGIN + $w);
             $pdf->SetX($xPos);
             $pdf->SetFont('Times', 'B', 8);
             $text = "Total: " . $owed_arrears;
             $pdf->MultiCell($w, 12, $text, 1, 'R');
         }
     } else {
         $no_arrears = "Ksh. 0.00";
         $xPos = $page_width - (self::PDF_MARGIN + $w);
         $pdf->SetX($xPos);
         $pdf->MultiCell($w, 8, $no_arrears, 0, 'R');
         $pdf->Ln();
     }
     // Collection Summary
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetX(0 + self::PDF_MARGIN);
     $pdf->SetFont('Arial', 'B', 10);
     $pdf->SetTextColor(24);
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, 'Collection Summary', 'B', 'C');
     $pdf->Ln();
     $summary_aligns = array('R', 'R');
     $pdf->SetAligns($summary_aligns);
     $cell_width = $pdf->get_page_width() / 4;
     $summary_widths = array($cell_width, $cell_width);
     $pdf->SetWidths($summary_widths);
     $pdf->Ln();
     $xPos = $page_width - (self::PDF_MARGIN + $cell_width * 2);
     //$pdf->SetX($xPos);
     $pdf->RowX($rent_collection_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($paid_arrears_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($summary_collection_array);
     $pdf->Ln();
     $pdf->Ln();
     //$pdf->SetX($xPos);
     $pdf->RowX($mgt_fee_array);
     //$pdf->SetX($xPos);
     //$pdf->RowX($net_amount_array);
     $pdf->Ln();
     $pdf->Ln();
     // Outline Expenses
     $pdf->SetX(0 + self::PDF_MARGIN);
     $pdf->SetFont('Arial', 'B', 10);
     $pdf->SetTextColor(24);
     $exp_incurred = "Expenses for the Period ";
     $exp_incurred .= strftime("%B %d, %Y", $timestamp_start);
     $exp_incurred .= " to " . strftime("%B %d, %Y", $timestamp_end);
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, $exp_incurred, 'B', 'C');
     $pdf->Ln();
     if ($expenses_obj->num_rows >= 1) {
         $col_count_expenses = $this->columnCount($expenses_obj);
         $expense_headings = $this->columnHeadings($expenses_obj);
         $expense_widths = array();
         $w = ($page_width - 2 * self::PDF_MARGIN) / $col_count_expenses;
         for ($i = 0; $i < $col_count_expenses; $i++) {
             $expense_widths[$i] = $w;
         }
         //$pdf->SetWidths(array(70, 70, 70, 70, 70, 70));
         $pdf->SetWidths($expense_widths);
         $expense_aligns = array();
         $a = 'R';
         for ($i = 0; $i < $col_count_expenses; $i++) {
             $expense_aligns[$i] = $a;
         }
         $pdf->SetAligns($expense_aligns);
         $pdf->SetFont('Helvetica', 'B', 8);
         $pdf->RowX($expense_headings, false);
         $pdf->SetFont('Helvetica', '', 7);
         while ($row = $expenses_obj->fetch_row()) {
             $pdf->RowX($row);
         }
         if (!is_null($total_expenses)) {
             $xPos = $page_width - (self::PDF_MARGIN + $w);
             $pdf->SetX($xPos);
             $pdf->SetFont('Times', 'B', 8);
             $text = "Total: " . $total_expenses;
             $pdf->MultiCell($w, 12, $text, 1, 'R');
         }
     } else {
         $no_expenses = "Ksh. 0.00";
         $xPos = $page_width - (self::PDF_MARGIN + $w);
         $pdf->SetX($xPos);
         $pdf->MultiCell($w, 8, $no_expenses, 0, 'R');
         $pdf->Ln();
     }
     $pdf->Ln();
     $pdf->Ln();
     $pdf->SetX(0 + self::PDF_MARGIN);
     $pdf->SetFont('Arial', 'B', 10);
     $pdf->SetTextColor(24);
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, 'Banking', 'B', 'C');
     $banking_aligns = array('R', 'R');
     $pdf->SetAligns($banking_aligns);
     $cell_width = $pdf->get_page_width() / 4;
     $banking_widths = array($cell_width, $cell_width);
     $pdf->SetWidths($banking_widths);
     $pdf->Ln();
     $xPos = $page_width - (self::PDF_MARGIN + $cell_width * 2);
     //$pdf->SetX($xPos);
     $pdf->RowX($net_amount_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($total_expenses_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($net_banking_array);
     $pdf->Ln();
     $pdf->MultiCell($pdf->get_page_width() - self::PDF_MARGIN * 2, 8, 'Analysis', 'B', 'C');
     $pdf->Ln();
     $currProp = Property::findById($prop_id);
     $num_of_rooms = $currProp->getNumRooms();
     $num_occupied_rooms = $currProp->getNumRoomsOccupied();
     $occupancy_level = $currProp->calcOccupancyLevel();
     $monthly_collection = $currProp->calcExpectedMonthlyCollection();
     $expected_collection = $currProp->calcExpectedCollectionForPeriod($start, $end);
     $percentage_collection = $currProp->calcCollectionPercentageForPeriod($start, $end);
     $period = $currProp->getNumMonthsInPeriod($start, $end);
     $period = '( ' . $period . ' Month[s] )';
     $num_rooms_array = array(0 => 'Number of Rooms in Property', 1 => $num_of_rooms);
     $occupied_rooms_array = array(0 => 'No. of Occupied Rooms', 1 => $num_occupied_rooms);
     $occupancy_level_array = array(0 => 'Occupancy Level (%)', 1 => $occupancy_level . '%');
     $expected_monthly_collection = array(0 => 'Expected Monthly Collection', 1 => $monthly_collection);
     $amount_collected_array = array(0 => "Total Amount Collected in Period{$period}", 1 => $collection_summary);
     $expected_collection_array = array(0 => 'Expected Collection for Period', 1 => $expected_collection);
     $percentage_collection_array = array(0 => 'Collection Level (%)', 1 => $percentage_collection . '%');
     //$pdf->SetX($xPos);
     $pdf->RowX($num_rooms_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($occupied_rooms_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($occupancy_level_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($expected_monthly_collection);
     //$pdf->SetX($xPos);
     $pdf->RowX($amount_collected_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($expected_collection_array);
     //$pdf->SetX($xPos);
     $pdf->RowX($percentage_collection_array);
     $pdf->Output($filename, 'D');
 }
 /**
  * Get the final amount deposited into landlords account
  * after deducting both management fee and expenses for a 
  * a particular property over a specified period of time
  * @param string $start Date string specifying start of the period
  * @param string $end Date string specifying end of the period
  */
 public function getFinalBanking($start, $end)
 {
     $rent = new Rent();
     $net_banking = $rent->calcNetBanking($this->id, $start, $end);
     return $net_banking;
 }
        $mesg = "Receipt for the transaction could not be generated. An invalid value was sent through the URL";
        $session->message($mesg);
        redirect_to("tenants.php");
    } else {
        switch ($type) {
            case "deposit":
                $deposit = Deposit::findByTenantId($tenant_id);
                break;
            case "deposit_kplc":
                $dpt_kplc = DepositKPLC::findByTenantId($tenant_id);
                break;
            case "deposit_eldowas":
                $dpt_eldowas = DepositEldowas::findByTenantId($tenant_id);
                break;
            case "rent":
                $rent = Rent::findById($id);
                break;
            case "arrears":
                $ap = ArrearsPaid::findById($id);
                break;
        }
        //echo var_dump($deposit);
    }
} else {
    $mesg = "Operation Not Supported";
    $session->message($mesg);
    redirect_to("tenants.php");
}
//$deposit = Deposit::findById(1);
//$deposit = Deposit::findByTenantId(1);
//echo var_dump($deposit);
 /**
  * @param int $id
  * @return Rent
  */
 function get($id)
 {
     $result = $this->db()->execute('SELECT R.*, S.login FROM Rents R ' . 'LEFT JOIN Servers S ON R.id = S.idRent ' . 'WHERE R.id = %d', $id);
     return Rent::fromRecordSet($result);
 }
 // Continue with processing
 $rent = new Rent();
 $rent->setPropertyId($prop_id);
 $rent->setTenantId($tenant_id);
 $rent->setStartPeriod($start_date);
 $rent->setEndPeriod($end_date);
 $rent->setDatePaid();
 $rent->setPaymentAmount($amount);
 $rent->generateReceiptNo();
 $rent->setPaymentMode($mode);
 $rent->setReceivingAgent($session);
 $rent->setRemarks($remarks);
 //echo var_dump($rent);
 if ($tenant->payRent($rent, $start_date, $end_date)) {
     Logger::getInstance()->logAction("RENT", $amount, "Rent of {$tenant->getFullName()} for {$rent->getMonth()}");
     $last_id = Rent::lastPaymentId();
     /*$session->sessionVar('start', $start_date);
     		$session->sessionVar('end', $end_date)*/
     if ($mode == "cheque") {
         // Cheque Payment
         $session->sessionVar("type", "rent");
         $mesg = "Payment details saved";
         $session->message($mesg);
         redirect_to("cheque_details.php?tid={$tenant_id}&id={$last_id}");
     } else {
         // Cash Payment
         $session->message("Payment recorded");
         redirect_to("receipt.php?tid={$tenant_id}&id={$last_id}&type=rent");
         //redirect_to("tenant.php?tid={$tenant_id}");
     }
 } else {
    $session->message($mesg);
    redirect_to('view_users.php');
}
$prop_id = $session->sessionVar("prop_id");
//echo var_dump($prop_id);
if (isset($_POST['submit'])) {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    if (empty($start_date) || empty($end_date)) {
        $err = "Choose a month from which to display rent payments from";
    } elseif (!valid_date_range($start_date, $end_date)) {
        $err = "Reports can only be specified monthly";
    } else {
        // continue with processing
        //echo var_dump($prop_id);
        $payments = Rent::getPaymentsFromProperty($prop_id, $start_date, $end_date);
        //echo var_dump($payments);
        $arrears_paid = ArrearsPaid::getPaidArrearsForProperty($prop_id, $start_date, $end_date);
        $arrears = Arrears::getOutstandingArrearsForProperty($prop_id, $start_date, $end_date);
        $expenses = Expense::findByPeriodForProperty($prop_id, $start_date, $end_date);
        $deposits = Deposit::findPaymentsForPeriodByProperty($prop_id, $start_date, $end_date);
        $refunds = Deposit::findRefundsForPeriodByProperty($prop_id, $start_date, $end_date);
        $refunds_kplc = DepositKPLC::findRefundsForPeriodByProperty($prop_id, $start_date, $end_date);
        $refunds_eldowas = DepositEldowas::findRefundsForPeriodByProperty($prop_id, $start_date, $end_date);
        $records = CollectionReport::buildRecords($prop_id, $start_date, $end_date);
        $deductions = CollectionReport::calcTotalDeductionsForPeriod($prop_id, $start_date, $end_date);
        //echo var_dump($records);
        //echo var_dump($arrears_paid);
    }
} elseif (isset($_POST['report'])) {
    // Generate PDF report
 /**
  * Calculate the sum of all payments made by a tenant during a specifed
  * period of time. This includes monthly rent, rent arrears paid, house 
  * deposit, KPLC deposit and ELDOWAS deposit
  * @param string $start Date string specifying start of the period
  * @param string $end Date string specifying end of the period
  * @return int $total_payments
  */
 public function calcPaymentsMadeDuringPeriod($start, $end)
 {
     $total_amount = 0;
     $rent = Rent::findByPeriodForTenant($this->id, $start, $end);
     $arrers_paid = ArrearsPaid::calcAmountPaidByTenantDuringPeriod($this->id, $start, $end);
     $arrers_paid = $this->_formatCurrencyString($arrers_paid);
     $deposit = Deposit::findByPeriodForTenant($this->id, $start, $end);
     $kplc = DepositKPLC::findByPeriodForTenant($this->id, $start, $end);
     $eldowas = DepositEldowas::findByPeriodForTenant($this->id, $start, $end);
     $rent_amount = !is_null($rent) ? $this->_formatCurrencyString($rent->getPaymentAmount()) : 0;
     $deposit_amount = !is_null($deposit) ? $this->_formatCurrencyString($deposit->getPaymentAmount()) : 0;
     $kplc_amount = !is_null($kplc) ? $this->_formatCurrencyString($kplc->getPaymentAmount()) : 0;
     $eldowas_amount = !is_null($eldowas_amount) ? $this->_formatCurrencyString($eldowas->getPaymentAmount()) : 0;
     $total_amount = $rent_amount + $deposit_amount + $arrers_paid + $kplc_amount + $eldowas_amount;
     return number_format($total_amount);
 }