<?php
error_log("--------------------starting--------------------");
// ini_set('display_errors', 1);
// error_reporting(E_ALL);

require_once __DIR__ . '/config.php';
require __DIR__ . '/google_sheet/vendor/autoload.php';
require __DIR__ . '/vendor/autoload.php';
define("MAIL_HOST", 'kangaroo.growsimple.io');
define("MAIL_USERNAME", 'info@kangaroo.growsimple.io');
define("MAIL_PASSWORD", 'Rr8i+U6Qbd)h');
define("ADMIN_EMAIL", 'info@kangaroo.growsimple.io');
define("MAIL_ENCRYPTION", 'SSL');
define("MAIL_PORT", 465);
require 'vendor/phpmailer/phpmailer/src/Exception.php';
require 'vendor/phpmailer/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/phpmailer/src/SMTP.php';
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
use Google\Client;
class Report
{

	private function getGoogleClient()
	{
		$client = new Google\Client();
		$client->setApplicationName('Dashboard Data');
		$client->setScopes('https://www.googleapis.com/auth/spreadsheets');
		$client->setAuthConfig('google_sheet/credentials.json');
		$client->setAccessType('offline');
		$client->setPrompt('select_account consent');
		$tokenPath = __DIR__ . '/google_sheet/token.json';
		if (file_exists($tokenPath)) {
			$accessToken = json_decode(file_get_contents($tokenPath), true);
			$client->setAccessToken($accessToken);
		}

		// If there is no previous token or it's expired.
		if ($client->isAccessTokenExpired()) {
			$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
			$newAccessToken = $client->getAccessToken();
			$accessToken = array_merge($accessToken, $newAccessToken);
			file_put_contents($tokenPath, json_encode($accessToken));
		}
		return $client;
	}
	private function getDataFromSpreadsheet()
	{
		try {

			$googleClient = $this->getGoogleClient();
			$service = new Google\Service\Sheets($googleClient);
			$spreadsheetId = '1vh5hRk7UT5_JwOweJzMTfurjxRLZri7sR_u0OODA74k';
			$range = '1 Client -Appointments!A2:k';
			$response = $service->spreadsheets_values->get($spreadsheetId, $range);
			$values = $response->getValues();
			$huddle = "<h2 style='margin-top:40px'>New Daily schedule for Huddles</h2>";
			$current_day = date("l");
			if ($current_day == 'Monday') {
				$huddle .= "<div>Monday-<br>1130- LG/Billing/Client tickets- Tommy/ Nick<br>12pm- Branding/ Launches- Tommy/Nick/Emilee/J<br><br>
				Daily Huddle- Mondays<br>
				- Payout closers-t Tommy<br>
				- Payout closers-t Tommy<br>
				- Reactivation Check (Tommy/Carole)<br>
				- Branding Check (J)<br>
				- Lead Gen Check (Tommy/Nick)<br>
				- Check launches/onboardings-Emilee<br>
				</div>";
			} elseif ($current_day == 'Tuesday') {
				$huddle .= "<div>Tuesday-<br>1130-closers call- client issues/ sales- Closers/ Nick<br>12- Reactivations/Appt setting-Carole/Tommy/Nick</div>";

			} elseif ($current_day == 'Wednesday') {
				$huddle .= "<div>Wednesday-<br>11 - Financial huddle- Nick/ Jojo<br>1130 - client issues/ team projects -Tommy + Nick/ Carole</div>";

			} elseif ($current_day == 'Thursday') {
				$huddle .= "<div>Thursday-<br>1130 - closers</div>";

			} elseif ($current_day == 'Friday') {
				$huddle .= "<div>Friday-<br>1130- Full team huddle</div>";

			}
			$appinments_html = '
				<html>
				<body><h2>#1 Client Success Account - Appointments for day</h2><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
				<th style=" border:1px solid black;padding: 5px">Client Name</th>
				<th style=" border:1px solid black;padding: 5px">Requested Time</th>
				<th style=" border:1px solid black;padding: 5px">Time Zone</th>
				<th style=" border:1px solid black;padding: 5px">Added date</th>
				<th style=" border:1px solid black;padding: 5px">Calender</th>
                <th style=" border:1px solid black;padding: 5px">Notes</th>
				</tr>
				';

			////////////////////to get the renual date from monday.com/////////////
			$current_date = date("Y-m-d");
			foreach ($values as $val) {
				$date = date_create($val[1]);
				$requested_date = date_format($date, "Y-m-d");
				if ($requested_date == $current_date && $val[6] == 'ynCWf3Y4AEJ7hfQ4lVWE') {
					$appinments_html .= '<tr>
												<td style=" border:1px solid black;padding: 5px">' . $val[0] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[1] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[9] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[2] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[3] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[5] . '</td>
											</tr>';

				}
			}
			$appinments_html .= '</table></body></html>';
			$appinments_html1 = '
				<html>
				<body><h2 style="margin-top:40px">#3 Sale Team Account - Appointments for day</h2><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
				<th style=" border:1px solid black;padding: 5px">Client Name</th>
				<th style=" border:1px solid black;padding: 5px">Requested Time</th>
				<th style=" border:1px solid black;padding: 5px">Time Zone</th>
				<th style=" border:1px solid black;padding: 5px">Added date</th>
				<th style=" border:1px solid black;padding: 5px">Calender</th>
				<th style=" border:1px solid black;padding: 5px">Notes</th>
				</tr>
				';
			foreach ($values as $val) {
				$date = date_create($val[1]);
				$requested_date = date_format($date, "Y-m-d");
				if ($requested_date == $current_date && $val[6] == 'Yjkpt82b8Vqjm10Ir9tD') {
					$appinments_html1 .= '<tr>
												<td style=" border:1px solid black;padding: 5px">' . $val[0] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[1] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[9] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[2] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[3] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val[5] . '</td>

											</tr>';

				}

			}
			$appinments_html1 .= '</table></body></html>';
			////////////////////for rewewal of the day///////////////////////////
			$token = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjI2Mjc1NTI2LCJ1aWQiOjEwNTI2MTgyLCJpYWQiOiIyMDE5LTExLTA3VDIwOjUyOjU1LjAwMFoiLCJwZXIiOiJtZTp3cml0ZSIsImFjdGlkIjo0NzcxMTY4LCJyZ24iOiJ1c2UxIn0.sLv4V0xFn9klbIL1S_H4s4PQCIF8CkzWXYJ_m5Kgq3A';
			$apiUrl = 'https://api.monday.com/v2';
			$headers = ['Content-Type: application/json', 'Authorization: ' . $token];
			$query = 'query {boards (ids:455873195) { groups (ids: "imported_pulses__rows_63942") { items { name  column_values{ title text } }}}}';
			$data = @file_get_contents($apiUrl, false, stream_context_create([
				'http' => [
					'method' => 'GET',
					'header' => $headers,
					'content' => json_encode(['query' => $query]),
				]
			]));
			$responseContent = json_decode($data, true);
			echo "<pre>";
			$current_date = date("Y-m-d");
			$arr = $responseContent['data']['boards'][0]['groups'][0]['items'];
			$renewal_of_day = '
					<html>
					<body><h2 style="margin-top:40px">Renewals Of the Day</h2><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
					<th style=" border:1px solid black;padding: 5px">Client Name</th>
					<th style=" border:1px solid black;padding: 5px">Renewal Date</th>
					</tr>
					';
			foreach ($arr as $val) {
				if ($val['column_values'][4]['text'] == $current_date) {
					$renewal_of_day .= '<tr>
					<td style=" border:1px solid black;padding: 5px">' . $val['name'] . '</td>
					<td style=" border:1px solid black;padding: 5px">' . $val['column_values'][4]['text'] . '</td>
					</tr>';
				}
			}
			$renewal_of_day .= '</table></body></html>';
			///////////////////////////////////////reactivation of the day///////////////
			$token = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjI2Mjc1NTI2LCJ1aWQiOjEwNTI2MTgyLCJpYWQiOiIyMDE5LTExLTA3VDIwOjUyOjU1LjAwMFoiLCJwZXIiOiJtZTp3cml0ZSIsImFjdGlkIjo0NzcxMTY4LCJyZ24iOiJ1c2UxIn0.sLv4V0xFn9klbIL1S_H4s4PQCIF8CkzWXYJ_m5Kgq3A';
			$apiUrl = 'https://api.monday.com/v2';
			$headers = ['Content-Type: application/json', 'Authorization: ' . $token];
			$query = 'query {boards (ids:2455602594) { groups (ids: "topics") { items { name  column_values{ title text } }}}}';
			//$query = 'query {boards (ids: 2455602594 ){ groups {id title }}}';
			$data = @file_get_contents($apiUrl, false, stream_context_create([
				'http' => [
					'method' => 'GET',
					'header' => $headers,
					'content' => json_encode(['query' => $query]),
				]
			]));
			$responseContent = json_decode($data, true);
			$current_day = date("l");
			$reactivations = $responseContent['data']['boards'][0]['groups'][0]['items'];
			$reactivations_of_day = '
				<html>
				<body><h2 style="margin-top:40px">Reactivations Of the Day</h2><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
				<th style=" border:1px solid black;padding: 5px">Client Name</th>
				<th style=" border:1px solid black;padding: 5px">Priority</th>
				</tr>
				';
			foreach ($reactivations as $val) {
				if ($val['column_values'][1]['text'] == 1) {
					if ($current_day == 'Monday' || $current_day == 'Tuesday' || $current_day == 'Wednesday' || $current_day == 'Thursday' || $current_day == 'Friday') {
						$reactivations_of_day .= '<tr>
												<td style=" border:1px solid black;padding: 5px">' . $val['name'] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val['column_values'][1]['text'] . '</td>
												</tr>';

					}
				}
				if ($val['column_values'][1]['text'] == 2) {
					if ($current_day == 'Monday' || $current_day == 'Wednesday' || $current_day == 'Friday') {
						$reactivations_of_day .= '<tr>
												<td style=" border:1px solid black;padding: 5px">' . $val['name'] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val['column_values'][1]['text'] . '</td>
												</tr>';

					}
				}
				if ($val['column_values'][1]['text'] == 3) {
					if ($current_day == 'Tuesday' || $current_day == 'Thursday') {
						$reactivations_of_day .= '<tr>
												<td style=" border:1px solid black;padding: 5px">' . $val['name'] . '</td>
												<td style=" border:1px solid black;padding: 5px">' . $val['column_values'][1]['text'] . '</td>
												</tr>';
					}
				}
			}
			$reactivations_of_day .= '</table></body></html>';
			$query_renewal = 'query {boards (ids:455873195) { groups (ids: "imported_pulses__rows_63942") { items { name  column_values{ title text } }}}}';
			$data_renewal = @file_get_contents($apiUrl, false, stream_context_create([
				'http' => [
					'method' => 'GET',
					'header' => $headers,
					'content' => json_encode(['query' => $query_renewal]),
				]
			]));
			$responseContent_renewal = json_decode($data_renewal, true);
			$next_renewal = '';
			$reactivations_renewal = $responseContent_renewal['data']['boards'][0]['groups'][0]['items'];
			$current_day = date("l");
			if ($current_day == 'Monday') {
				$next_renewal = '
										<html>
										<body><h2 style="margin-top:40px">Mortgage forming</h2>
										<p>7 days out</p><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
										<th style=" border:1px solid black;padding: 5px">Client Name</th>
										<th style=" border:1px solid black;padding: 5px">Next Renewal Date</th>
										</tr>
										';
				$current_date = date("Y-m-d");
				$sevenDaysLater = date("Y-m-d", strtotime('+6 days'));
				foreach ($reactivations_renewal as $val) {
					if (!empty($val['column_values'][4]['text'])) {
						$renewal_date = date_create($val['column_values'][4]['text']);
						$renewal_date = date_format($renewal_date, "Y-m-d");
						if ($renewal_date <= $sevenDaysLater && $current_date <= $renewal_date) {
							$next_renewal .= '<tr>
													<td style=" border:1px solid black;padding: 5px">' . $val['name'] . '</td>
													<td style=" border:1px solid black;padding: 5px">' . $renewal_date . '</td>
													</tr>';

						}
					}
				}
				$next_renewal .= '</table></body></html>';
			}
			////////////////////////////7 days launch/////
			$last_7days_live='';
			if ($current_day == 'Monday') {
				$spreadsheetId = '1vh5hRk7UT5_JwOweJzMTfurjxRLZri7sR_u0OODA74k';
				$range = 'Live Billing!A2:AJ';
				$response = $service->spreadsheets_values->get($spreadsheetId, $range);
				$values = $response->getValues();
				$current_date = date("Y-m-d");
				$sevenDaysearlier = date("Y-m-d", strtotime('-6 days'));
				$last_7days_live = '<html>

										<body><h2>7 days Launch Window </h2><table style=" border:1px solid black ;padding: 5px" >
										<tr style=" border:1px solid black;padding: 5px">
										<th style=" border:1px solid black;padding: 5px">Client Name</th>
										<th style=" border:1px solid black;padding: 5px">Live On</th>
										</tr>
										';
				$live_as = [];

				foreach ($values as $val_launch) {
					if (isset($val_launch[3]) && strpos(trim($val_launch[3]), 'Live as') === 0) {
						$live_as[] = ['client' => $val_launch[0], 'date' => $val_launch[3]];
					}
				}
				foreach ($live_as as $live_client) {
					$date = substr($live_client['date'], -10);
					$time_input = strtotime($date);
					$launch_date = date("Y-m-d", $time_input);
					if ($launch_date >= $sevenDaysearlier) {
						$last_7days_live .= '<tr>
											<td style=" border:1px solid black;padding: 5px">' . $live_client['client'] . '</td>
											<td style=" border:1px solid black;padding: 5px">' . $live_client['date'] . '</td>
											</tr>';
					}
				}
				$last_7days_live .= '</table></body></html>';
			}
			$twillio_data = '<html>
									<body><h2 style="margin-top:40px">Twillio usages over $100</h2><table style=" border:1px solid black ;padding: 5px" ><tr style=" border:1px solid black;padding: 5px">
									<th style=" border:1px solid black;padding: 5px">Friendly Name</th>
									<th style=" border:1px solid black;padding: 5px">SID</th>
									<th style=" border:1px solid black;padding: 5px">Usages</th>
									</tr>
									';
			$sid = "AC38af2d635db67338efd5cd106b9a2a28";
			$token = "a84d4aebe8a63174c8f5300b26922570";
			$twilio = new Twilio\Rest\Client($sid, $token);
			$accounts = $twilio->api->v2010->accounts->read();
			foreach ($accounts as $record) {
				$sub_account_sid = $record->sid;
				$friendly_name = $record->friendlyName;
				$total = 0;
				$curl = curl_init();
				$api_url = "https://api.twilio.com/2010-04-01/Accounts/" . $sub_account_sid . "/Usage/Records/ThisMonth.json?Category=totalprice";
				curl_setopt($curl, CURLOPT_URL, $api_url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($curl, CURLOPT_USERPWD, "$sid:$token");
				$response = curl_exec($curl);
				$response = json_decode($response, true);
				foreach ($response as $res) {
					if (is_array($res)) {
						foreach ($res as $re) {
							$total = $re['price'];
							if ($total > 100) {
								$twillio_data .= '<tr>
											<td style=" border:1px solid black;padding: 5px">' . $friendly_name . '</td>
											<td style=" border:1px solid black;padding: 5px">' . $sub_account_sid . '</td>
											<td style=" border:1px solid black;padding: 5px">' . $total . '</td>
											</tr>';

							}
						}
					}
				}

			}

			$twillio_data .= '</table></body></html>';
			////////////////////////////////////////////////////////////////////
			$appinments_html = $appinments_html . $appinments_html1 . $renewal_of_day . $reactivations_of_day;
			$facebook_add = '<h2>Facebook Ads Reporting Link:&nbsp;<a href="https://datastudio.google.com/s/uZJVcZqqI1Q">https://datastudio.google.com/s/uZJVcZqqI1Q</a></h2>';
			$appinments_html = $next_renewal . $last_7days_live . $huddle . $appinments_html . $facebook_add . $twillio_data;

			$recipients = array(
			'mediasimplifiednow@gmail.com',
			'mediasimplified.ben@gmail.com',
			'mediasimplified.c@gmail.com',
			'mediasimplified.emilee@gmail.com',
			'mediasimplified.joann@gmail.com',
			'mediasimplified.jordan@gmail.com',
			'mediasimplified.megan@gmail.com',
			'nick@mediasimplifiednow.com',
			'mediasimplified.sales@gmail.com',
			'mediasimplified.tommy@gmail.com',
			'rector.julia91@gmail.com',
			'mediasimplified.tech@gmail.com'
			);
			// $recipients = array(
			// 	'renukarani1994@gmail.com',
			// );
			$mail = new PHPMailer();
			// $mail->SMTPDebug = 1;                      //Enable verbose debug output
			$mail->isSMTP();                                            //Send using SMTP
			$mail->Host = MAIL_HOST;                     //Set the SMTP server to send through
			$mail->SMTPAuth = true;                                   //Enable SMTP authentication
			$mail->Username = MAIL_USERNAME;                     //SMTP username
			$mail->Password = MAIL_PASSWORD;                               //SMTP password
			$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
			$mail->Port = MAIL_PORT;
			$mail->setFrom('info@kangaroo.growsimple.io', 'Growsimple Team');
			$mail->addReplyTo('info@kangaroo.growsimple.io', 'Growsimple Team');
			foreach ($recipients as $recipient) {
						    $mail->addAddress($recipient);
						}
			$mail->Subject = 'Appointments For Today';
			$mail->Body = $appinments_html;
			$mail->IsHTML(true);
			    if ($mail->send()) {
			 $this->logRequest(['message' => 'cron mail sent from appoinments_on_mail.php']);
			    }
		} catch (Exception $e) {
			$this->logRequest(['message' => $e->getMessage()]);
			return [
				'status'	=> 'error',
				'message'	=> $e->getMessage()
			];
		}
	}
	public function AppoinmentsOnMail()
	{
		$response = $this->getDataFromSpreadsheet();
	}

	private function logRequest($log_data = [])
	{
		$time = time();
		error_log("--------------------[START/" . $time . "]--------------------");
		$body = json_encode($_REQUEST);
		$body .= json_encode($log_data);
		$bodyLength = strlen($body);
		error_log($bodyLength ? $body : "(empty body)");
		error_log("---------------------[END/" . $time . "]---------------------");
	}
}
$report = new Report();
$report->AppoinmentsOnMail();
