<?php
/**
 * BusinessAdmin: administrative software for small companies
 * Copyright (C) 2015 Camil Staps (ViviSoft)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once('./index.php');
require_once('./login.php');
require('./header.php');
?>

<div id="wrapper">

	<?php require('nav.php'); ?>

	<div id="page-wrapper">
		<div class="row">
			<div class="col-lg-12">
				<h1 class="page-header">Welcome</h1>
			</div>
			<!-- /.col-lg-12 -->
		</div>
		<!-- /.row -->
		<div class="row">
			<div class="col-lg-3 col-md-3 col-sm-6">
				<?php
				$count = count(BusinessAdmin::getOfferIds($_pdo, array("`accepted` = 0")));
				?>
				<div class="panel panel-<?=($count==0 ? 'primary' : 'yellow')?>">
					<div class="panel-heading">
						<div class="row">
							<div class="col-xs-3">
								<i class="fa fa-briefcase fa-5x"></i>
							</div>
							<div class="col-xs-9 text-right">
								<div class="huge"><?=$count?></div>
								<!--<div>Unaccepted offers</div>-->
							</div>
						</div>
					</div>
					<a href="<?=Constants::url_external?>offers">
						<div class="panel-footer">
							<span class="pull-left">Unaccepted offers</span>
							<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
							<div class="clearfix"></div>
						</div>
					</a>
				</div>
			</div>
			<div class="col-lg-3 col-md-3 col-sm-6">
				<?php
				$count = count(BusinessAdmin::getOfferIds($_pdo, array("`accepted`=1", "`start_date` <= CURDATE()", "`end_date` >= CURDATE()")));
				?>
				<div class="panel panel-<?=($count==0 ? 'primary' : ($count < 3) ? 'green' : ($count < 5 ? 'yellow' : 'red'))?>">
					<div class="panel-heading">
						<div class="row">
							<div class="col-xs-3">
								<i class="fa fa-tasks fa-5x"></i>
							</div>
							<div class="col-xs-9 text-right">
								<div class="huge"><?=$count?></div>
								<!--<div>Active offers</div>-->
							</div>
						</div>
					</div>
					<a href="#panel-active-offers">
						<div class="panel-footer">
							<span class="pull-left">Active offers</span>
							<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
							<div class="clearfix"></div>
						</div>
					</a>
				</div>
			</div>
			<div class="col-lg-3 col-md-3 col-sm-6">
				<?php
				$count = count(BusinessAdmin::getOfferIds($_pdo, array("`accepted`=1", "`end_date` <= CURDATE()", "`invoice_date` IS NULL OR `invoice_date`='1970-01-01' OR `invoice_date`>CURDATE()")));
				?>
				<div class="panel panel-<?=($count==0 ? 'primary' : ($count < 3) ? 'green' : ($count < 5 ? 'yellow' : 'red'))?>">
					<div class="panel-heading">
						<div class="row">
							<div class="col-xs-3">
								<i class="fa fa-clock-o fa-5x"></i>
							</div>
							<div class="col-xs-9 text-right">
								<div class="huge"><?=$count?></div>
								<!--<div>Active offers</div>-->
							</div>
						</div>
					</div>
					<a href="#panel-finished-offers">
						<div class="panel-footer">
							<span class="pull-left" title="Offers that have been finished but for which no invoice has been sent yet">Finished offers</span>
							<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
							<div class="clearfix"></div>
						</div>
					</a>
				</div>
			</div>
			<div class="col-lg-3 col-md-3 col-sm-6">
				<?php
				$count = count(BusinessAdmin::getOfferIds($_pdo, array(
					"`invoice_date` > '1970-01-01'",
					"`invoice_date`<=CURDATE()",
					"NOT EXISTS (SELECT * FROM `".Constants::db_prefix."payment` WHERE `offerId`=`".Constants::db_prefix."offer`.`id`)")));
				?>
				<div class="panel panel-<?=($count==0 ? 'primary' : 'yellow')?>">
					<div class="panel-heading">
						<div class="row">
							<div class="col-xs-3">
								<i class="fa fa-circle-o-notch fa-5x"></i>
							</div>
							<div class="col-xs-9 text-right">
								<div class="huge"><?=$count?></div>
								<!--<div>Open invoices</div>-->
							</div>
						</div>
					</div>
					<a href="#panel-open-invoices">
						<div class="panel-footer">
							<span class="pull-left">Open invoices</span>
							<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
							<div class="clearfix"></div>
						</div>
					</a>
				</div>
			</div>
		</div>
		<!-- /.row -->
		<div class="row">
			<div class="col-lg-12">
				<div class="panel panel-default" id="panel-active-offers">
					<div class="panel-heading">
						<i class="fa fa-tasks fa-fw"></i> Currently active offers
					</div>
					<!-- /.panel-heading -->
					<div class="panel-body">
						<?php
						$offers = BusinessAdmin::getOffers($_pdo, array("`accepted`=1", "`start_date` <= CURDATE()", "`end_date` >= CURDATE()"));
						$list = array();
						foreach ($offers as $offer) {
							$start = BusinessAdmin::formatDate($offer->getStartDate(), false);
							$end = BusinessAdmin::formatDate($offer->getEndDate(), false);
							$since = mktime(0,0,0,date("n"),date("j"),date("Y")) - $offer->getStartDate();
							$total = $offer->getEndDate() - $offer->getStartDate();
							$percentage = ($total == 0) ? 100 : round($since / $total * 100);

							// We want to sort on percentage (DESC) and secondly end date (ASC) so start date (DESC)
							$base = str_pad($percentage, 3, '0', STR_PAD_LEFT) . $offer->getStartDate();
							for ($i = 0; isset($list["$base-$i"]); $i++);
							$list["$base-$i"] = array(
								'start' => $start,
								'end' => $end,
								'id' => $offer->getId(),
								'contactClientName' => $offer->getContact()->getClient()->name,
								'percentage' => $percentage,
								'price_excl' => Constants::invoice_valuta . $offer->calculate(offer::SUBTOTAL),
								'price_incl' => Constants::invoice_valuta . $offer->calculate(offer::TOTAL)
							);
						}
						krsort($list, SORT_STRING);
						foreach ($list as $item) {
							echo "<p>#{$item['id']} to {$item['contactClientName']} ({$item['start']} - {$item['end']}; {$item['price_excl']} excl. VAT, {$item['price_incl']} incl. VAT)<span class='pull-right text-muted'>{$item['percentage']}% complete</span></p>
								<div class='progress progress-striped active' style='clear:both;'>
									<div class='progress-bar progress-bar-".($item['percentage'] < 60 ? 'info' : ($item['percentage'] < 80 ? 'warning' : 'danger'))."' style='width:{$item['percentage']}%;' aria-valuemax='100' aria-valuemin='0' aria-valuenow='{$item['percentage']}' role='progressbar'></div>
								</div>";
						}
						if (count($list) == 0) {
							echo "There are no currently active offers.";
						}
						?>
					</div>
					<!-- /.panel-body -->
				</div>
				<!-- /.panel -->
			</div>
			<div class="col-lg-6 col-md-6">
				<div class="panel panel-default" id="panel-finished-offers">
					<div class="panel-heading" title="Offers that have been finished but for which no invoice has been sent yet">
						<i class="fa fa-clock-o fa-fw"></i> Finished offers
					</div>
					<!-- /.panel-heading -->
					<div class="panel-body table-responsive">
						<table class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>#</th>
									<th>Contact</th>
									<th>Offer ended</th>
								</tr>
							</thead>
							<tbody>
								<?php
								$offers = BusinessAdmin::getOffers($_pdo, array("`accepted`=1", "`end_date` <= CURDATE()", "`invoice_date` IS NULL OR `invoice_date`='1970-01-01' OR `invoice_date`>CURDATE()"));
								foreach ($offers as $offer) {
									echo "<tr>";
									echo "<td>{$offer->getId()}</td>";
									echo "<td>{$offer->getContact()->getClient()->name}</td>";
									echo "<td>".BusinessAdmin::formatDate($offer->getEndDate(), false)."</td>";
									echo "</tr>";
								}
								if (count($offers) == 0) {
									echo "<tr><td colspan='3'>There are no offers that need an invoice.</td></tr>";
								}
								?>
							</tbody>
						</table>
					</div>
					<!-- /.panel-body -->
				</div>
				<!-- /.panel -->
			</div>
			<div class="col-lg-6 col-md-6">
				<div class="panel panel-default" id="panel-open-invoices">
					<div class="panel-heading">
						<i class="fa fa-circle-o-notch fa-fw"></i> Currently open invoices
					</div>
					<div class="panel-body table-responsive">
						<table class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>#</th>
									<th>Contact</th>
									<th>Invoice sent</th>
								</tr>
							</thead>
							<tbody>
								<?php
								$offers = BusinessAdmin::getOffers($_pdo, array(
									"`invoice_date` > '1970-01-01'",
									"`invoice_date`<=CURDATE()",
									"NOT EXISTS (SELECT * FROM `".Constants::db_prefix."payment` WHERE `offerId`=`".Constants::db_prefix."offer`.`id`)"));
								if (count($offers) == 0) {
									echo "<tr><td colspan='3'>There are no currently open invoices.</td></tr>";
								} else {
									foreach ($offers as $offer) {
										echo "<tr>";
										echo "<td>{$offer->getId()}</td>";
										echo "<td>{$offer->getContact()->getClient()->name}</td>";
										echo "<td>".BusinessAdmin::formatDate($offer->getInvoiceDate(), false)."</td>";
										echo "</tr>";
									}
								}
								?>
							</tbody>
						</table>
					</div>
					<!-- /.panel-body -->
				</div>
				<!-- /.panel -->
			</div>
		</div>
		<!-- /.row -->
		<div class="row">
			<div class="col-lg-12">
				<div class="panel panel-default" id="panel-timeline">
					<div class="panel-heading">
						<i class="fa fa-clock-o fa-fw"></i> Timeline
					</div>
					<!-- /.panel-heading -->
					<div class="panel-body">
						<ul class="timeline">
							<?php
							$offers = BusinessAdmin::getOffers($_pdo, array('`accepted`=1'));
							$list = array();
							$sort_list = array();
							foreach ($offers as $offer) {
								$temp = array(
									'id' => $offer->getId(),
									'contact' => $offer->getContact()->getName(),
									'assignments' => '',
									'assignments_header' => ''
								);
								foreach ($offer->getAssignments() as $assignment) {
									$temp['assignments'] .= "<b>{$assignment->getTitle()}</b><br/><span class='smaller'>(".Constants::invoice_valuta."{$assignment->calculate(assignment::SUBTOTAL)} excl. VAT, ".Constants::invoice_valuta."{$assignment->calculate(assignment::TOTAL)} incl. VAT)</span><br/><p>{$assignment->getDescription()}</p>";
									$temp['assignments_header'] .= "<b>{$assignment->getTitle()}</b><br/><span class='smaller'>(".Constants::invoice_valuta."{$assignment->calculate(assignment::SUBTOTAL)} excl. VAT, ".Constants::invoice_valuta."{$assignment->calculate(assignment::TOTAL)} incl. VAT)</span><br/>";
								}
								$list[] = array_merge($temp, array('type' => 'start', 'time' => $offer->getStartDate(), 'description' => 'Offer started'));
								$sort_list[] = $offer->getStartDate() . $offer->getId() . 0;
								$list[] = array_merge($temp, array('type' => 'end', 'time' => $offer->getEndDate(), 'description' => 'Offer ended'));
								$sort_list[] = $offer->getEndDate() . $offer->getId() . 1;
								if ($offer->getInvoiceDate() > 0) {
									$list[] = array_merge($temp, array('type' => 'invoice', 'time' => $offer->getInvoiceDate(), 'description' => 'Invoice sent'));
									$sort_list[] = $offer->getInvoiceDate() . $offer->getId() . 2;
									if ($offer->getPaymentReceived() > 0) {
										$list[] = array_merge($temp, array('type' => 'payment_received', 'time' => $offer->getPaymentReceived(), 'description' => 'Payment received'));
										$sort_list[] = $offer->getPaymentReceived() . $offer->getId() . 3;
									}
								}
							}
							array_multisort($sort_list, SORT_DESC, $list);
							foreach ($list as $item) {
								if ($item['time'] > time()) {
									continue;
								}
								echo "<li" . ($item['type'] != 'start' ? ' class="timeline-inverted"' : '') . ">";
								switch ($item['type']) {
									case 'start':			 echo "<div class='timeline-badge info' title='{$item['description']}'><i class='fa fa-circle-o-notch'></i></div>"; break;
									case 'end':			   echo "<div class='timeline-badge primary' title='{$item['description']}'><i class='fa fa-circle-o'></i></div>"; break;
									case 'invoice':		   echo "<div class='timeline-badge warning' title='{$item['description']}'><i class='fa fa-check-circle-o'></i></div>"; break;
									case 'payment_received':  echo "<div class='timeline-badge success' title='{$item['description']}'><i class='fa fa-".Constants::fa_valuta."'></i></div>"; break;
								}
								echo "<div class='timeline-panel'>";
								echo "<div class='timeline-heading'><h4 class='timeline-title'>#{$item['id']} to {$item['contact']}: {$item['description']}</h4><p><small class='text-muted'><i class='fa fa-clock-o fa-fw'></i> ".BusinessAdmin::formatDate($item['time'],false,true,true)."</small></p></div>";
								switch ($item['type']) {
									case 'start':			 echo "<div class='timeline-body'>{$item['assignments']}</div>"; break;
									default:				  echo "<div class='timeline-body'>{$item['assignments_header']}</div>";
								}
								echo "</div>";
								echo "</li>";
							}
							if (count($list) == 0) {
								echo '<li class="timeline-inverted">
										<div class="timeline-badge info"><i class="fa fa-check-circle-o"></i></div>
										<div class="timeline-panel">
											<div class="timeline-heading"><h4 class="timeline-title">Welcome to BusinessAdmin!</div>
											<div class="timeline-body">When you start adding projects, a timeline will appear here.</div>
										</div>
									</li>';
							}
							?>
						</ul>
					</div>
					<!-- /.panel-body -->
				</div>
				<!-- /.panel -->
			</div>
		</div>
	</div>
	<!-- /#page-wrapper -->

</div>
<!-- /#wrapper -->