<?php
if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');
	
//if (!is_admin($current_user)) die('Nie masz wystarczających uprawnień');

if (isset($_GET['request'])) {
    if ($_GET['request'] == 'showHeaders')
        echo loadHeaders($_GET['user_id'], $_GET['date_from'], $_GET['date_to'], $_GET['answered'], $_GET['seen'], $_GET['deleted'], $_GET['io'], 'in');
    
	if ($_GET['request'] == 'showHeaders_outbox')
        echo loadHeaders($_GET['user_id'], $_GET['date_from'], $_GET['date_to'], null             , null         , $_GET['deleted'], $_GET['io'], 'out');
     
	if ($_GET['request'] == 'showMail')
        echo loadMail($_GET['mail_id'], $_GET['user_id']);
    
	if ($_GET['request'] == 'showAttachments')
        echo loadAttachments($_GET['mail_id'], $_GET['user_id']);
} else
    initSearch();

function initSearch() {
    $xtpl = new XTemplate('modules/Emails/allList.html');
    $db = $GLOBALS['db'];

    //generate users list
    //AND id!='9adce0e8-d0c2-dc41-83f8-4eb9333b6c77'
    //list without user Marek Wiśniewski
    $query = "
	SELECT 
		id, 
		first_name, 
		last_name 
	FROM 
		users 
	WHERE 
		deleted = 0 
	AND 
		employee_status = 'Active' 
	AND 
		id != '9adce0e8-d0c2-dc41-83f8-4eb9333b6c77';
	";
	
//	print_r($query);
//	exit;
	
    $result = $db->query($query);
    $user_list = '';
    $user_list.='<select size="' . $result->num_rows . '" id="user_list" onClick="javascript:showHeaders()">';
	
    while ($row = $db->fetchByAssoc($result)) {
        $user_list.='<option value="' . $row['id'] . '">' . $row['first_name'] . ' ' . $row['last_name'] . '</option>';
    }
	
    $user_list.='</select>';
    $xtpl->assign("USER_LIST", $user_list);

    $xtpl->parse("main");
    $xtpl->out("main");
}

function loadHeaders($user_id, $date_from, $date_to, $answered, $seen, $deleted, $io, $in_out) {
    $db = $GLOBALS['db'];

	$io = trim($io);
	
    if ($in_out != 'in')
        $in_out = 'out';
    
	//var_dump($in_out);
	
	$whereConditions = array();
	
	if(strlen($io))
		switch($in_out){
			default:
			case 'in':
				array_push($whereConditions, 'ec.`fromaddr` LIKE \'%' . $io . '%\'');
				break;
			case 'out':
				array_push($whereConditions, 'ec.`toaddr` LIKE \'%' . $io . '%\'');
				break;
		}
	
	//echo '<pre>';
	//var_dump($whereConditions);
	//echo '</pre>';
	
	$query = "
		SELECT 
			ec.ie_id, 
			ec.subject, 
			ec.message_id, 
			ec.fromaddr, 
			ec.toaddr, 
			ec.senddate, 
			ec.alllist_text_id 
		FROM 
			email_cache AS ec 
		INNER JOIN 
			email_alllist_texts as et ON et.id=ec.alllist_text_id 
		WHERE 
			et.ie_id IN 
				(
					SELECT id FROM inbound_email WHERE group_id='" . $user_id . "'
				)
		AND 
			et.in_out LIKE '" . $in_out . "'";
			
	$query .= $whereConditions ? (' AND '  . implode(' AND ', $whereConditions)) : '';
    
	//print_r($query); 
	//exit;
	
	if (($date_from != '') && ($date_to != ''))
    {
		$query.=" AND senddate BETWEEN (SELECT DATE_FORMAT('" . $date_from . "', '%Y%m%d')) AND (SELECT DATE_FORMAT('" . $date_to . "', '%Y%m%d'))";
    } else {
        if ($date_from != '')
            $query.=" AND senddate >= '" . $date_from . "'";
			
        if ($date_to != '')
            $query.=" AND senddate <= '" . $date_to . "'";
    }
	
    $query.=" AND alllist_text_id IS NOT NULL";
    $query.=" ORDER BY senddate DESC";

    $result = $db->query($query);

    $header_list = '';
	$header_list .= '<table id ="header_table" cellpadding="1px">';
	$header_list .= '<tr id="header_table_head_row">';
	$header_list .= '<td width=500><b>Temat</b></td>';
	
	switch($in_out){
			default:
			case 'in':
				$header_list .= '<td width=250><b>Nadawca</b></td>';
				break;
			case 'out':
				$header_list .= '<td width=250><b>Odbiorca</b></td>';
				break;
		}
	 
	$header_list .= '<td width=150><b>Data otrzymania</b></td>';
	$header_list .= '</tr>';
					
    $s = 0;
    $a = 0;
    $d = 0;

    while ($row = $db->fetchByAssoc($result)) {
        if ($row['deleted'] == 1) {
            $przekreP = '<s>';
            $przekreK = '</s>';
        } else {
            $przekreP = '';
            $przekreK = '';
        }
		
        if ($row['answered'] == 1) {
            $podkreP = '<u>';
            $podkreK = '</u>';
        } else {
            $podkreP = '';
            $podkreK = '';
        }
		
        if ($row['seen'] == 0) {
            $pogruP = '<b>';
            $pogruK = '</b>';
        } else {
            $pogruP = '';
            $pogruK = '';
        }

        $subject = charsetEncode($row['subject']);
		$from = '';
        
		switch($in_out){
			default:
			case 'in':
				$from = charsetEncode($row['fromaddr']);
				break;
			case 'out':
				$from = charsetEncode($row['toaddr']);
				break;
		}

        $id = $row['alllist_text_id'];

        $header_list .= '<tr onMouseOver="this.className=\'highlight\'" onMouseOut="this.className=\'normal\'" onClick="this.className=\'selected\';javascript:showAttachments(\'' . $id . '\');javascript:showMail(\'' . $id . '\');">
							<td width=500>' . $podkreP . $przekreP . $pogruP . $subject . $podkreK . $przekreK . $pogruK . '</td>
							<td width=250>' . $podkreP . $przekreP . $pogruP . ($from) . $podkreK . $przekreK . $pogruK . '</td>
							<td width=150>' . $podkreP . $przekreP . $pogruP . $row['senddate'] . $podkreK . $przekreK . $pogruK . '</td>
						</tr>
						';
							
        if ($row['seen'] == 1)
            $s++;
        if ($row['answered'] == 1)
            $a++;
        if ($row['deleted'] == 1)
            $d++;
    }

    $header_list.='</table>';
    $header_list.='</select></td><td valign="top" style="padding-left: 10px;">';

    return $header_list;
}

function loadHeaders_outbox($user_id, $date_from, $date_to, $deleted) {
    $db = $GLOBALS['db'];

    $query = "SELECT id, assigned_user_id, name, deleted, date_sent FROM emails WHERE assigned_user_id='" . $user_id . "' AND (status='sent' OR status='archived') AND (type='out' OR type='archived') AND mailbox_id IS NULL";

    if (($date_from != '') && ($date_to != ''))
        $query.=" AND date_sent BETWEEN (SELECT DATE_FORMAT('" . $date_from . "', '%Y%m%d')) AND (SELECT DATE_FORMAT('" . $date_to . "', '%Y%m%d'))";
    else {
        if ($date_from != '')
            $query.=" AND date_sent >= '" . $date_from . "'";
			
        if ($date_to != '')
            $query.=" AND date_sent <= '" . $date_to . "'";
    }
	
    if ($deleted == 0)
        $query.=" AND deleted=0";
		
    if ($deleted == 1)
        $query.=" AND deleted=1";
		
    $query.=" ORDER BY date_sent DESC";
    $result = $db->query($query);

    $emails = array();
    while ($row = $db->fetchByAssoc($result)) {
        $res = $db->query("SELECT email_address FROM email_addresses AS ea INNER JOIN emails_email_addr_rel AS eear ON (eear.email_address_id=ea.id AND eear.address_type='FROM' AND email_id='" . $row['id'] . "') INNER JOIN inbound_email AS ie ON (ie.email_user!=ea.email_address AND ie.group_id='" . $user_id . "')");

        if ($res->num_rows == 0)
            $emails[] = $row;
    }

    //$header_list.='<select size="'.$result->num_rows.'" id="header_list" onClick="javascript:showMail()">';
    $header_list = '<table id ="header_table" cellpadding="1px"><tr id="header_table_head_row">
						<td width=650><b>Temat</b></td>
						<td width=150><b>Data wysłania</b></td>
					</tr>';
    $s = 0;
    $a = 0;
    $d = 0;

    //while ($row = $db->fetchByAssoc($result)) {
    foreach ($emails as $row) {
        if ($row['deleted'] == 1) {
            $przekreP = '<s>';
            $przekreK = '</s>';
        } else {
            $przekreP = '';
            $przekreK = '';
        }

        $subject = charsetEncode($row['name']);
        //$subject = charsetEncode($row['id']);
        //$from = fix_text($row['fromaddr']);

        $header_list.='<tr onMouseOver="this.className=\'highlight\'" onMouseOut="this.className=\'normal\'">
								<td width=500>
								<a href="index.php?module=Emails&action=DetailView&record=' . $row['id'] . '" target="new">
								' . $podkreP . $przekreP . $pogruP . $subject . $podkreK . $przekreK . $pogruK . '</a></td>
								<td width=150>' . $podkreP . $przekreP . $pogruP . $row['date_sent'] . $podkreK . $przekreK . $pogruK . '</td>
							</tr>';
        if ($row['seen'] == 1)
            $s++;
        if ($row['answered'] == 1)
            $a++;
        if ($row['deleted'] == 1)
            $d++;
    }
    $header_list.='</table>';
    //$header_list.='</select></td><td valign="top" style="padding-left: 10px;">';
    return $header_list;
}

function loadMail($id, $user_id) {
    $db = $GLOBALS['db'];
    $query = "SELECT description_html, attachments FROM email_alllist_texts WHERE id='" . $id . "';";
    $result = $db->query($query);
    $row = $db->fetchByAssoc($result);
    $text = htmlspecialchars_decode($row['description_html']);

	//return $query;
	
    //to fix images
	//
    //$attachments = explode(";", $row['attachments']);
    //$file_name = array();
    //if (count($attachments)>1)
    //foreach ($attachments as $file) {
    //$parts = explode("/", $file);
    //	$ext = substr($parts[count($parts)-1],strlen($parts[count($parts)-1])-4, 4);
    //	if (($ext=='.jpg') || ($ext=='.png') || ($ext=='.gif'))
    //	array_push($file_name, $parts[count($parts)-1]);
    //	}
	//
	//$text = str_replace('http://192.168.0.4/crm/cache//images/','modules/Emails/alllist_upload/'.$id.'/"',$text);
	//foreach ($file_name as $file)
    //$text = str_replace($id.'/"', $id.'/'.$file.'"', $text, 1);
	
    str_replace("\n", "<br>", $text);
    return $text;
}

function loadAttachments($id, $user_id) {
    $db = $GLOBALS['db'];
    $query = "SELECT attachments FROM email_alllist_texts WHERE id='" . $id . "';";
    $result = $db->query($query);
    $row = $db->fetchByAssoc($result);
    //$text = htmlspecialchars_decode($row['attachments']);
    $text = $row['attachments'];

    $attachments = explode(";", $row['attachments']);
    $return = ' ';
	
    if (count($attachments) == 1)
        return 'Załączników: 0<br><br>';
    else {
        //$return = "Załączników: ".(count($attachments)-1).'<br><br>';
       foreach ($attachments as $file) {
            $parts = explode("/", $file);
            $file_name = $parts[count($parts) - 1];
            $return.='<a target="new" href="modules/Emails/alllist_upload/' . $file . '">' . $file_name . '</a><br>';
        }
    }
    return $return;
}

//to fix headers charset
function charsetEncode($string) {
    $a = imap_mime_header_decode($string);
    $result = '';
	
    foreach ($a as $v)
        if ($v->charset != 'default')
            $result.=iconv($v->charset, "UTF-8", $v->text) . ' ';
			
    if ($result != '')
        return $result; 
	else
        return $string;
}