public function save_plan()
 {
     $vaccine = $this->input->post("vaccine");
     $dates = $this->input->post("dates");
     $amounts = $this->input->post("amounts");
     $existing_plans = Provisional_Plan::getCurrentPlan($vaccine);
     //First delete all the existing plans
     foreach ($existing_plans as $existing_plan) {
         $existing_plan->delete();
     }
     //Then add the new Plans
     $counter = 0;
     foreach ($dates as $date) {
         if (strlen($date) > 2) {
             $plan = new Provisional_Plan();
             $plan->vaccine = $vaccine;
             $plan->year = date('Y');
             $plan->expected_date = $dates[$counter];
             $plan->expected_amount = $amounts[$counter];
             $plan->modified_by = $this->session->userdata('user_id');
             $plan->save();
             $counter++;
         } else {
             continue;
         }
     }
     redirect("batch_management");
 }
	function download($national = "", $region = "", $district = "") {
		$title = "";
		if ($national > 0) {
			$title = "MOS Available at Central Vaccine Store";
		}
		if ($region > 0) {
			$region_object = Regions::getRegion($region);
			$title = "MOS Available at " . $region_object -> name;
		}
		if ($district > 0) {
			$district_object = Districts::getDistrict($district);
			$title = "MOS Available at " . $district_object -> name . " District Store";
		}
		$vaccines = Vaccines::getAll_Minified();
		$date = date("m/d/Y");
		$months_required = array();
		$data_buffer = "
			<style>
			table.data-table {
			table-layout: fixed;
			width: 700px;
			border-collapse:collapse;
			border:1px solid black;
			}
			table.data-table td, th {
			width: 100px;
			border: 1px solid black;
			}
			.leftie{
				text-align: left !important;
			}
			.right{
				text-align: right !important;
			}
			.center{
				text-align: center !important;
			}
			</style> 
			";
		$data_buffer .= "<table class='data-table'>";
		$data_buffer .= $this -> echoTitles();

		foreach ($vaccines as $vaccine_object) {
			$months_of_stock = array();
			$year = date('Y');
			$now = date('U');
			$population = 0;
			$stock_balance = 0;
			if ($national > 0) {
				$population = Regional_Populations::getNationalPopulation($year);
				$stock_balance = Disbursements::getNationalPeriodBalance($vaccine_object -> id, $now);
			}
			if ($region > 0) {
				$population = Regional_Populations::getRegionalPopulation($region, $year);
				$stock_balance = Disbursements::getRegionalPeriodBalance($region, $vaccine_object -> id, $now);
			}
			if ($district > 0) {
				$population = District_Populations::getDistrictPopulation($district, $year);
				$stock_balance = Disbursements::getDistrictPeriodBalance($district, $vaccine_object -> id, $now);
			}
			$population = str_replace(",", "", $population);
			$monthly_requirement = ceil(($vaccine_object -> Doses_Required * $population * $vaccine_object -> Wastage_Factor) / 12);
			$months_till_shipment = 0;
			if ($national > 0) {
				$months_of_stock = array();
				$year = date('Y');
				$now = date('U');
				$expected_delivery = Provisional_Plan::getNextDelivery($vaccine_object -> id);

				if (isset($expected_delivery[0])) {
					$next_shipment = $expected_delivery[0]['next_shipment'];
					$days_till_shipment = $expected_delivery[0]['difference'];
					if (isset($days_till_shipment)) {
						$months_till_shipment = number_format(($days_till_shipment / 30), 1);
					}
				}
			}
			if ($region > 0) {
				$months_till_shipment = 3;
				$next_shipment = "N/A";
			}
			if ($district > 0) {
				$months_till_shipment = 3;
				$next_shipment = "N/A";
			}

			$doses_needed = "N/A";
			if ($stock_balance > 0) {
				$months_left = number_format(($stock_balance / $monthly_requirement), 1);
			}
			if ($months_left > $months_till_shipment) {
				$doses_needed = "None";
			} else {
				$doses_needed = number_format((($months_till_shipment - $months_left) * $monthly_requirement), 2);
			}

			$monthly_requirement = number_format($monthly_requirement + 0);
			$data_buffer .= "<tr><td class='leftie'>" . $vaccine_object -> Name . "</td><td class='right'>" . number_format($stock_balance) . "</td><td class='center'>" . $months_left . "</td><td class='center'>" . $next_shipment . "</td><td class='center'>" . $months_till_shipment . "</td><td class='right'>" . $monthly_requirement . "</td><td class='right'>" . $doses_needed . "</td></tr>";

		}
		$data_buffer .= "</table>";
		$this -> generatePDF($data_buffer, $title);
		//echo $data_buffer;
	}
 function create_national_report()
 {
     $year = date('Y');
     $headers = "Summary Report for Vaccine Status in Kenya\n\t\nDepot: National Store\tReporting Date: " . date("d/m/Y") . "\t\n";
     $data = "Analytical Areas\t";
     $vaccines = Vaccines::getAll();
     $from = date("U", mktime(0, 0, 0, 1, 1, date('Y')));
     //This sets the begining date as the 1st of january of that particular year
     $to = date('U');
     //This sets the end date as the current time when the report is being generated
     //Loop all vaccines and append the vaccine name in the excel sheet content.
     foreach ($vaccines as $vaccine) {
         $data .= $vaccine->Name . "\t";
     }
     $data .= "\n";
     //New Line!
     //Begin adding data for the areas being analysed!
     $data .= "Annual Needs Coverage\t";
     //Loop all vaccines and append the needs coverage for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $population = Regional_Populations::getNationalPopulation($year);
         $yearly_requirement = $population * $vaccine->Doses_Required * $vaccine->Wastage_Factor;
         $vaccine_totals = Disbursements::getNationalReceiptsTotals($vaccine->id, $from, $to);
         $coverage = ceil($vaccine_totals / $yearly_requirement * 100);
         $data .= $coverage . "%\t";
     }
     $data .= "\n";
     //New Line
     $data .= "Stock Availability (Stock at Hand)\t";
     //Loop all vaccines and append the stock at hand for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $stock_at_hand = Disbursements::getNationalPeriodBalance($vaccine->id, $to);
         $data .= $stock_at_hand . "\t";
     }
     $data .= "\n";
     //New Line
     $data .= "Stock at Hand Forecast (In Months)\t";
     //Loop all vaccines and append the stock at hand forecast for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $population = Regional_Populations::getNationalPopulation($year);
         $population = str_replace(",", "", $population);
         $monthly_requirement = ceil($vaccine->Doses_Required * $population * $vaccine->Wastage_Factor / 12);
         $stock_at_hand = Disbursements::getNationalPeriodBalance($vaccine->id, $to);
         $forecast = $stock_at_hand / $monthly_requirement;
         $data .= $forecast . "\t";
     }
     $data .= "\n";
     //New Line
     $data .= "Shipments Expected Dates\t";
     //Loop all vaccines and append the shipments expected for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $plans = Provisional_Plan::getYearlyPlan($year, $vaccine->id);
         $plans_string = "";
         foreach ($plans as $plan) {
             $plans_string .= $plan->expected_date . " (" . $plan->expected_amount . ") ";
         }
         if (strlen($plans_string) < 1) {
             $plans_string = "None";
         }
         $data .= $plans_string . "\t";
     }
     $data .= "\n";
     //New Line
     $data .= "Shipments received Dates\t";
     //Loop all vaccines and append the shipments received for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $receipts = Batches::getYearlyReceipts($year, $vaccine->id);
         $receipts_string = "";
         foreach ($receipts as $receipt) {
             $receipts_string .= $receipt->Arrival_Date . " (" . $receipt->Total . ") ";
         }
         if (strlen($receipts_string) < 1) {
             $receipts_string = "None";
         }
         $data .= $receipts_string . "\t";
     }
     $data .= "\n";
     //New Line
     /*header("Content-type: application/vnd.ms-excel; name='excel'");
     	 header("Content-Disposition: filename=Country_Vaccine_Status_Summary.xls");
     	 // Fix for crappy IE bug in download.
     	 header("Pragma: ");
     	 header("Cache-Control: ");*/
     $result = $headers . $data;
     return $result;
 }
    public function get($year, $vaccine)
    {
        $receipts = Batches::getYearlyReceipts($year, $vaccine);
        $plans = Provisional_Plan::getYearlyPlan($year, $vaccine);
        $month_margins = array(0, 31, 60, 90, 121, 151, 182, 213, 243, 274, 304, 335, 366);
        $chart = '
<chart palette="2" caption="Provisional Plan" subcaption="For the year ' . $year . '" xAxisName="Date" yAxisName="Quantity"  showValues="0" alternateHGridColor="FCB541" alternateHGridAlpha="20" divLineColor="FCB541" divLineAlpha="50" canvasBorderColor="666666" baseFontColor="666666" lineColor="FCB541" xAxisMaxValue="366" xAxisMinValue="0">
<categories verticalLineColor="666666" verticalLineThickness="1">
<category label="Jan" x="0" showVerticalLine="1"/>
<category label="Feb" x="31" showVerticalLine="1"/>
<category label="Mar" x="60" showVerticalLine="1"/>
<category label="Apr" x="90" showVerticalLine="1"/>
<category label="May" x="121" showVerticalLine="1"/>
<category label="Jun" x="151" showVerticalLine="1"/>
<category label="Jul" x="182" showVerticalLine="1"/>
<category label="Aug" x="213" showVerticalLine="1"/>
<category label="Sep" x="243" showVerticalLine="1"/>
<category label="Oct" x="274" showVerticalLine="1"/>
<category label="Nov" x="304" showVerticalLine="1"/>
<category label="Dec" x="335" showVerticalLine="1"/>
<category label="Jan" x="366" showVerticalLine="1"/>
</categories> 
<dataSet seriesName="Planned Arrivals" color="009900" anchorSides="3" anchorRadius="7" anchorBgColor="D5FFD5" anchorBorderColor="009900">';
        foreach ($plans as $plan) {
            $date = $plan->expected_date;
            $quantity = $plan->expected_amount;
            $split_date = explode("/", $date);
            $month = $split_date[0] - 1;
            $month_delimiter = $month_margins[$month];
            $day = $split_date[1];
            $x_axis_value = $month_delimiter + $day;
            $chart .= '<set y="' . $quantity . '" x="' . $x_axis_value . '" toolText="' . $quantity . " Expected on " . $date . '"/>';
        }
        $chart .= '
</dataSet>
 
<dataSet seriesName="Actual Arrivals" color="0000FF" anchorSides="7" anchorRadius="7" anchorBgColor="C6C6FF" anchorBorderColor="0000FF">';
        foreach ($receipts as $receipt) {
            $date = $receipt->Arrival_Date;
            $quantity = $receipt->Total;
            $split_date = explode("/", $date);
            $month = $split_date[0] - 1;
            $month_delimiter = $month_margins[$month];
            $day = $split_date[1];
            $x_axis_value = $month_delimiter + $day;
            $chart .= '<set y="' . $quantity . '" x="' . $x_axis_value . '" toolText="' . $quantity . " (Batch No. " . $receipt->Batch_Number . ") Arrived on " . $date . '"/>';
        }
        $chart .= '
</dataSet>
<styles>
<definition>
<style name="Anim1" type="animation" param="_xscale" start="0" duration="1"/>
<style name="Anim2" type="animation" param="_alpha" start="0" duration="0.6"/>
<style name="DataShadow" type="Shadow" alpha="40"/>
</definition>
<application>
<apply toObject="DIVLINES" styles="Anim1"/>
<apply toObject="HGRID" styles="Anim2"/>
<apply toObject="DATALABELS" styles="DataShadow,Anim2"/>
</application>
</styles>
</chart>
';
        echo $chart;
    }
 function create_national_report()
 {
     $year = date('Y');
     $total_vaccines = Vaccines::getTotalNumber();
     $total_vaccines *= 2;
     $html = "<table border='2px solid black'>";
     $html .= "<tr ><th rowspan=3>Analytical Areas</th><th style='text-align: center' colspan=" . $total_vaccines . ">Summary Report for Vaccine Status in Kenya</th></tr>";
     $html .= "<tr ><th style='text-align: center' colspan=" . $total_vaccines . ">Depot: National Store Reporting Date: " . date("d/m/Y") . "</th></tr>";
     $headers = "Summary Report for Vaccine Status in Kenya\n\t\nDepot: National Store\tReporting Date: " . date("d/m/Y") . "\t\n";
     $data = "Analytical Areas\t";
     $vaccines = Vaccines::getAll();
     $from = date("U", mktime(0, 0, 0, 1, 1, date('Y')));
     //This sets the begining date as the 1st of january of that particular year
     $to = date('U');
     //This sets the end date as the current time when the report is being generated
     //Loop all vaccines and create a table data element for it
     $html .= "<tr>";
     foreach ($vaccines as $vaccine) {
         $html .= "<td colspan=2 style='background-color:#" . $vaccine->Tray_Color . "'>" . $vaccine->Name . "</td>";
     }
     $html .= "</tr>";
     //New Line!
     //Begin adding data for the areas being analysed!
     $html .= "<tr><td class='title'>Annual Needs Coverage</td>";
     //Loop all vaccines and append the needs coverage for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $population = Regional_Populations::getNationalPopulation($year);
         $yearly_requirement = $population * $vaccine->Doses_Required * $vaccine->Wastage_Factor;
         $vaccine_totals = Disbursements::getNationalReceiptsTotals($vaccine->id, $from, $to);
         $coverage = ceil($vaccine_totals / $yearly_requirement * 100);
         $html .= "<td colspan=2>" . $coverage . "%</td>";
     }
     $html .= "</tr>";
     $html .= "<tr><td class='title'>Number of Days of Stock Outage</td>";
     //Loop all vaccines and append the needs coverage for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $html .= "<td colspan=2>N/A</td>";
     }
     $html .= "</tr>";
     //New Line
     $html .= "<tr><td class='title'>Stock Availability (Stock at Hand)</td>";
     //Loop all vaccines and append the stock at hand for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $stock_at_hand = Disbursements::getNationalPeriodBalance($vaccine->id, $to);
         $html .= "<td colspan=2>" . $stock_at_hand . "</td>";
     }
     $html .= "</tr>";
     //New Line
     $html .= "<tr><td class='title'>Stock at Hand Forecast (In Months)</td>";
     //Loop all vaccines and append the stock at hand forecast for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         $population = Regional_Populations::getNationalPopulation($year);
         $population = str_replace(",", "", $population);
         $monthly_requirement = ceil($vaccine->Doses_Required * $population * $vaccine->Wastage_Factor / 12);
         $stock_at_hand = Disbursements::getNationalPeriodBalance($vaccine->id, $to);
         $forecast = $stock_at_hand / $monthly_requirement;
         $forecast = number_format($forecast, 2, '.', '');
         $html .= "<td colspan=2>" . $forecast . "</td>";
     }
     $html .= "</tr>";
     //New Line
     $html .= "<tr><td class='title'>Shipments Expected/Received Dates</td>";
     //Loop all vaccines and append the shipments expected for that particular vaccine in that store
     foreach ($vaccines as $vaccine) {
         //Get and display the expected dates
         $plans = Provisional_Plan::getYearlyPlan($year, $vaccine->id);
         $plans_string = "";
         $html .= "<td><table>";
         foreach ($plans as $plan) {
             $plans_string = $plan->expected_date . " (" . $plan->expected_amount . ") ";
             $html .= "<tr><td class='no_border'>" . $plans_string . "</td></tr>";
         }
         if (strlen($plans_string) < 1) {
             $plans_string = "None";
             $html .= "<tr><td class='no_border'>" . $plans_string . "</td></tr>";
         }
         $html .= "</table></td>";
         $receipts = Batches::getYearlyReceipts($year, $vaccine->id);
         $receipts_string = "";
         $html .= "<td><table>";
         foreach ($receipts as $receipt) {
             $receipts_string = $receipt->Arrival_Date . " (" . $receipt->Total . ") ";
             $html .= "<tr><td class='no_border'>" . $receipts_string . "</td></tr>";
         }
         if (strlen($receipts_string) < 1) {
             $receipts_string = "None";
             $html .= "<tr><td class='no_border'>" . $receipts_string . "</td></tr>";
         }
         $html .= "</table></td>";
     }
     $html .= "</tr>";
     //New Line
     //New Line
     /*header("Content-type: application/vnd.ms-excel; name='excel'");
     	 header("Content-Disposition: filename=Country_Vaccine_Status_Summary.xls");
     	 // Fix for crappy IE bug in download.
     	 header("Pragma: ");
     	 header("Cache-Control: ");*/
     $result = $headers . $data;
     $html .= "</table>";
     return $html;
 }