<?php
require('fpdf.php');
require_once('class.phpmailer.php');
require_once("../function.php");

$transit_id = $_POST['transit_id'];  //15

if($transit_id == "" || $_POST['token'] == ""){
	$response["success"] = 0;
	$response["message"] = "Please enter required value.";
	echo json_encode($response);
	exit();
}
//$agent_id = $_POST['agent_id'];    //12
$agent_id = token_auth($_POST['token']);

$email1 = ""; 
$email2 = ""; 
$email3 = "";
$email4 = "";
$email5 = "";

$carrierName = "";
$callPurpose = "";

/*$con = mysql_connect("localhost","delshani_rtrs","[;o^#h=&Z~(p");

if (!$con)
{
  die('Could not connect: ' . mysql_error());
}*/

//mysql_select_db("delshani_armsonline", $con);
mysql_select_db(DB_ARMS, $con);

$result_company = mysql_query("SELECT * FROM transit_email_rtr WHERE transit_id = $transit_id");

	if (mysql_num_rows($result_company) > 0) {
    
	
    while ($row = mysql_fetch_assoc($result_company)) {
        // temp user array
       
		$email1 = $row["email1"];
		$email2 = $row["email2"];
		$email3 = $row["email3"];
		$email4 = $row["email4"];
		$email5 = $row["email5"];
		//var_dump($row);
    }
}

$result_call_purpose = mysql_query("SELECT tv.carrier, tv.purpose_text, t.picture, t.eta FROM transit_view AS tv LEFT JOIN transit AS t ON tv.trans_id = t.transit_id WHERE tv.trans_id = $transit_id");

if (mysql_num_rows($result_call_purpose) > 0) 
{
	while ($row = mysql_fetch_assoc($result_call_purpose)) {
        // temp user array
       
		$carrierName = strtoupper($row["carrier"]);
		$callPurpose = $row["purpose_text"];
		$cover_image = $row["picture"];
		$eta 		 = date("M jS, Y", strtotime($row["eta"]));
    }
}

//var_dump($cover_image);
	mysql_close($con);

$pdf_name = "task_".date("Y-m-d-H-m-s").".pdf";
$pdf_location = "pdf_files/".$pdf_name;

define(CARRIER, $carrierName);

class PDF extends FPDF
{
	// Page header
	function Header()
	{
		// Logo
		if ( $this->PageNo() !== 1 ) {

			//$this->Image('http://www.portagent.mu/images/logo.gif',245,2,30,0,'GIF');
			// Arial bold 15
			$this->SetFont('Arial','B',20);
			// Move to the right
			$this->Cell(95);
			// Title
			$this->Cell(40,10,CARRIER,0,0,'L');
			//Change color for underline 
			$this->SetDrawColor(205, 209, 209);
			//Added line under title.
			$this->SetLineWidth(0.5);
			//Get y-axis position 
			$lineY = $this->GetY();
			//set line position
			$this->Line(120,$lineY+10, 155,$lineY+10);
			// Line break
			$this->Ln(20);
		}
	}

	// Page footer
	function Footer()
	{
		if ( $this->PageNo() !== 1 ) {
			// Position at 1.5 cm from bottom
			$this->SetY(-15);
			// Arial italic 8
			$this->SetFont('Arial','I',8);
			// Page number
			$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
		}
	}
}

// databae connectivity
$con_reportiong = mysql_connect("localhost","delshani_rtrs","[;o^#h=&Z~(p");

if (!$con_reportiong)
  {
  die('Could not connect: ' . mysql_error());
  }



//mysql_select_db("delshani_reporting", $con_reportiong);
mysql_select_db(DB_RTR, $con_reportiong);

$result = mysql_query("SELECT * FROM event WHERE transit_id = $transit_id AND agent_id = $agent_id AND status = 1 ORDER BY sent_time ");


// Instanciation of inherited class
$pdf = new PDF();
$pdf->AliasNbPages();
//$pdf->SetAutoPageBreak(true);
$pdf->SetLineWidth(0.9);
$pdf->AddPage('L');
$pdf->SetFont('Arial','B',27);

$imgX = 10;
$imgY = 40;
$mod = 2;

if (mysql_num_rows($result) > 0) {

if(!$cover_image){
	$cover_image = "images/bg-cover.jpg";
	$logo_img = "images/mail-logo.png";
}

$cover_top = "../images/cover-top-v3.png";



$pdf->Image("../".$cover_image,0,90,299); /// Image property

/*if($logo_img)
	$pdf->Image("../".$logo_img,255,100,30); /// Image property*/

$pdf->Image($cover_top,0,0,299); /// Image property

$pdf->SetTextColor(255,255,255);
$pdf->Cell(42);



$carrierName = strtoupper($carrierName);
$pdf->Cell(40,10,$carrierName,0,0);

$phone = 'Phone: +230 5252 2122';
$email = 'operations@portagent.mu';
$title = 'Real Time Reporting';
$desc  = 'The system, deployed in 2013, allows our ground ops team to use pre-programmable mobile devices to report each steps of a ship call in real time. Where required, instantaneous pictures of the events are attached to the email. All ship calls serviced are currently supported with this system.';

$pdf->Cell(100);

$pdf->SetFont('Arial','',9);

$pdf->Cell(0,5,$phone,0,2);

$pdf->Cell(0,5,$email,0,1);

$pdf->SetFont('Arial','B',13);
$pdf->ln(13);
$pdf->Cell(135);
$pdf->Cell(0,5,$title,0,1);
$pdf->ln(1);
$pdf->SetFont('Arial','',12);
$pdf->SetTextColor(128,214,244);
$pdf->Cell(88);
$pdf->MultiCell(135,5,$desc,0,L);

$pdf->SetTextColor(255,255,255);

$pdf->ln(10);
$pdf->Cell(42);
$pdf->Cell(20,5,$eta,0,0);
$pdf->Cell(150);
$pdf->Cell(0,5,"Port Louis",0,1);

	$i = 0;
	$j = 0;
    while ($row = mysql_fetch_assoc($result)) {
       
	   
		$title 			= $row["title"];
		$reported_time 	= $row["sent_time"];
		$des 			= $row["description"];
        $pic_location 	= $row["picture"];
		

		//var_dump($row);
		$pdf->SetTextColor(14, 61, 144);

		if($i%3 == 0 || $i==0)
		{
			$pdf->AddPage('L');
			$imgX = 10;
			$imgY = 20;

			$pdf->SetDrawColor(108, 118, 117);

			$pdf->SetLineWidth(0.5);
			$lineY = $pdf->GetY();
			$pdf->Line($imgX,$lineY+10, $imgX + 200,$lineY+10);
			$pdf->Ln(15);
			$pdf->SetFont('Arial','B',12);

			$pdf->Cell(5);
			$pdf->Cell(10,5,"Task",0,0, 'L');
			$pdf->Cell(35);
			$pdf->Cell(10,5,"Time",0,0, 'L');
			$pdf->Cell(25);
			$pdf->Cell(20,5,"Task detail",0, 0,'L');
			$pdf->SetFont('Arial','',12);

			$pdf->Ln(5);
			$pdf->SetLineWidth(0.5);
			$lineY = $pdf->GetY();
			$pdf->Line($imgX,$lineY+5, $imgX + 200,$lineY+5);
			$pdf->Ln(8);

			$pdf->SetDrawColor(209, 244, 252);
		}

		$pdf->SetFont('Arial','',8);

		$lineY = $pdf->GetY();
		$pdf->Cell(5);
		$pdf->MultiCell(35,5,$title,0,'L');

		/*$lineX = $pdf->GetX();
		echo $lineX."##";*/
		$pdf->SetY($lineY);
		$pdf->Cell(47);

		$pdf->MultiCell(30,5,$reported_time,0,'L');

		/*$lineX = $pdf->GetX();
		echo $lineX."@@";*/
		$pdf->SetY($lineY);
		$pdf->Cell(80);

		$pdf->MultiCell(120,5,$des,0,'L');
		$img_ext = 0;
		if(strlen($pic_location)!=0 || $pic_location != "")
		{
			$pic_array_type = explode(".", $pic_location);
			$type = $pic_array_type[1];
			//var_dump($type);
			if($type != "null"){
				//$pdf->SetY($lineY);
				$pdf->Cell(30);
				//list($width, $height, $t, $attr) = getimagesize("../".$pic_location);
				$pdf->Image("../".$pic_location,225,$lineY + 5,0, 25); /// Image property
				$img_ext = 1;
				//echo $height."$$";
				$pdf->Ln(15);
			}
			
			
		}
		
		//echo $i."##";
		if($j%2 !== 0 || $j == 0)
		{
			//echo "Here I am";
			//$imgY = $imgY + 50;
			$pdf->Ln(2);
			$pdf->SetLineWidth(0.5);
			$lineY = $pdf->GetY();
			$pdf->Line($imgX,$lineY+3, $imgX + 300,$lineY+3);
			$pdf->Ln(5);


		}

		
		//$imgY = $imgY + 90;
		
		$pdf->Image("../images/right-line.png",280,0,100); /// Image property
		$i = $i+1;
		$j = $j+1;

		if($j%3 == 0) $j = 0;
    }
}
else{
	// failed to insert row
        $response["success"] = 0;
        $response["message"] = "There is no completed task.";
       
        echo json_encode($response);
        exit();
}

$pdf->Output($pdf_location);

// email sent

$mail = new PHPMailer(); // defaults to using php "mail()"


$body = "Good day,<br> Please find attached the real time report for the port call of the ".$carrierName." at Port-Louis, Mauritius for ".$callPurpose.".<br> We hope you will find this <b>unique and pioneering service brought to you by PAS </b> of good value. <br><br> Best Regards <br> The PAS (Mauritius) Team ";

$body = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("ops@portagent.mu","PAS - Agent");

$mail->SetFrom("ops@portagent.mu", "PAS - Agent");



$mail->AddAddress("operations@portagent.mu");
$mail->AddAddress("accounts@portagent.mu");
$mail->AddAddress("director@portagent.mu");
$mail->AddAddress("ops@portagent.mu");
$mail->AddAddress("projects@portagent.mu");
$mail->AddAddress("tapas.sutradhar@portagent.mu");


if(strlen($email1)!=0)
{
$mail->AddAddress($email1);
}
if(strlen($email2)!=0)
{
	$mail->AddAddress($email2);
}
if(strlen($email3)!=0)
{
	$mail->AddAddress($email3);
}
if(strlen($email4)!=0)
{
	$mail->AddAddress($email4);
}

if(strlen($email5)!=0)
{
	$mail->AddAddress($email5);
}


$mail->Subject    = $carrierName." :Real Time Report Summary";

$mail->AltBody    = "Real Time Report from PAS (Mauritius)"; // optional, comment out and test

$mail->MsgHTML($body);

$mail->AddAttachment($pdf_location);      // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
$email_sent = 0;

if(!$mail->Send()) {
 
 $email_sent = 0;
 
} else {
  $email_sent = 1;
 }

// insert to event_pdf table

// array for JSON response
$response = array();
//die;
if($email_sent){
	$result_insert = mysql_query("INSERT INTO event_pdf(transit_id,agent_id,pdf_location,email_sent) VALUES($transit_id,$agent_id,'$pdf_location',$email_sent)");

    if ($result_insert) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Mail Send Successfully";

        echo json_encode($response);
		
    }
    else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
       
        echo json_encode($response);
		
    }  
}
 else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
       
        echo json_encode($response);
		
    }   

?>