<?php

function can_upload_project_gallery_image($Mode)
{
    if(!($_POST['project_id'] > 0)){
        display_error("Please select a project");
        return false;
    }
    
    if(!($_POST['section_id'] > 0)){
        display_error("Please select a project section");
        return false;
    }

    if ($Mode == 'ADD_ITEM' && (!isset($_FILES['filename']) || $_FILES['filename']['size'] == 0)){
	display_error(_("Please select an image file."));
        return false;
    }
    
    if(isset($_FILES['filename']['name']) && strlen($_FILES['filename']['name']) > 0){
        if($_FILES['filename']['type'] != 'image/jpeg'){
            display_error(_("Only jpg files allowed."));
            return false;
        }
        
        if($_FILES['filename']['size'] > 1048576){
            display_error(_("Allowed maximum file size is 1 mb."));
            return false;
        }
    }

    return true;
}

function upload_project_gallery_image($Mode, $selected_id)
{
    
    if(!can_upload_project_gallery_image($Mode))
    {
        return;
    }


    //$content = base64_encode(file_get_contents($_FILES['filename']['tmp_name']));
		$tmpname = $_FILES['filename']['tmp_name'];

		$dir =  company_path()."/project_images";
		if (!file_exists($dir))
		{
			mkdir ($dir,0777);
			$index_file = "<?php\nheader(\"Location: ../index.php\");\n?>";
			$fp = fopen($dir."/index.php", "w");
			fwrite($fp, $index_file);
			fclose($fp);
		}

		$filename = basename($_FILES['filename']['name']);
                $filename = str_replace(" ", "_", $filename);
                
		$filesize = $_FILES['filename']['size'];
		$filetype = $_FILES['filename']['type'];

		// file name compatible with POSIX
		// protect against directory traversal
		if ($Mode == 'UPDATE_ITEM')
		{
		    $row = get_project_gallery_image($selected_id);
		    if ($row['image_name'] == ""){
        		exit();
                    }
			
                    $unique_name = $row['unique_name'];
                    if ($filename && file_exists($dir."/".$unique_name)){
			unlink($dir."/".$unique_name);
                    }
		}
		else{
			$unique_name = uniqid('').".jpg";
                }

    
                
                
		//save the file
		move_uploaded_file($tmpname, $dir."/".$unique_name);

		if ($Mode == 'ADD_ITEM')
		{
//			add_project_gallery_image($_POST['filterType'], $_POST['trans_no'], $_POST['description'],
//				$filename, $unique_name, $filesize, $filetype);
			add_project_gallery_image($_POST['project_id'], $_POST['description'], $filename, $_POST['image_date'],
				$_POST['section_id'], $unique_name, $filetype, $filesize);
                                
			display_notification(_("File has been uploaded.")); 
		}
		else
		{
			update_project_gallery_image($selected_id, $_POST['description'], $filename, $_POST['image_date'],
				$_POST['section_id'], $unique_name, $filetype, $filesize); 
                        
			display_notification(_("File has been updated.")); 
		}
}


function viewing_controls()
{
	global $selected_id;
	
    start_table(TABLESTYLE_NOBORDER);
	start_row();
//	systypes_list_cells(_("Type:"), 'filterType', null, true);
            project_list_cells(_("Project:"), 'project_id', null,   _('Select a Project'), true);
            if (list_updated('project_id')){
                    $selected_id = -1;;
            }

	end_row();
    end_table();
    
    start_table(TABLESTYLE_NOBORDER);
	start_row();
            date_cells("From Date: ", 'from_date', '', null, -90, 0, 0, null, true);
            date_cells("To Date: ", 'to_date', '', null, 0, 0, 0, null, true);
            project_sections_list_cells("Section: ", 'filtering_section_id', $_POST['project_id'], null, '', true);
            
        end_row();
    end_table(1);
}

function trans_view($trans)
{
	return get_trans_view_str($trans["type_no"], $trans["trans_no"]);
}

function edit_link($row)
{
  	return button('Edit'.$row["id"], _("Edit"), _("Edit"), ICON_EDIT);
}

function view_link($row)
{
  	return button('view'.$row["id"], _("View"), _("View"), ICON_VIEW);
}

function download_link($row)
{
  	return button('download'.$row["id"], _("Download"), _("Download"), ICON_DOWN);
}

function delete_link($row)
{
  	return button('Delete'.$row["id"], _("Delete"), _("Delete"), ICON_DELETE);
}

function format_image_file_size($row)
{
  	return number_format($row["filesize"]/1024, 0)." kb";
}

function thumbnail_image($row)
{
        $stock_img_link = get_project_gallery_image_link($row['id'], 100);
        return $stock_img_link;
}

function display_rows($project_id, $section_id, $from_date_, $to_date_)
{
        $from_date = date2sql($from_date_); 
        $to_date = date2sql($to_date_);
    
	$sql = get_sql_for_project_gallery_images($project_id, $section_id, $from_date, $to_date);
	$cols = array(
            _("Id") ,
            _("Date") => array('type'=>'date'),
            _("Section"),            
            _("Filename"),            
	    _("Description"),
	    _("Size") => array('fun'=>'format_image_file_size', 'align'=>'right'),
//	    _("Filetype") => array('name'=>'filetype'),
	    _("Image") => array('fun'=>'thumbnail_image', 'align'=>'center'),
	    	array('insert'=>true, 'fun'=>'edit_link'),
	    	array('insert'=>true, 'fun'=>'view_link'),
	    	array('insert'=>true, 'fun'=>'download_link'),
	    	array('insert'=>true, 'fun'=>'delete_link')
	    );	
		$table =& new_db_pager('trans_tbl', $sql, $cols);

		$table->width = "80%";

		display_db_pager($table);
}


function download_project_gallery_image($download_id)
{
    global $Ajax;
    
	$row = get_project_gallery_image($download_id);
	if ($row['image_name'] != "")
	{
		if(in_ajax()) {
			$Ajax->redirect($_SERVER['PHP_SELF'].'?dl='.$download_id);
		} else {
			$type = ($row['filetype']) ? $row['filetype'] : 'application/octet-stream';	
                        header("Content-type: ".$type);
                        header('Content-Length: '.$row['filesize']);
                        header('Content-Disposition: attachment; filename='.$row['image_name']);
                        echo file_get_contents(company_path()."/project_images/".$row['unique_name']);
                        exit();
		}
	}	
}


function view_project_gallery_image($view_id)
{
    global $Ajax;
    
	$row = get_project_gallery_image($view_id);
	if ($row['image_name'] != "")
	{
		if(in_ajax()) {
			$Ajax->popup($_SERVER['PHP_SELF'].'?vw='.$view_id);
		} 
                else 
                    {
			$type = ($row['file_type']) ? $row['file_type'] : 'application/octet-stream';	
                        header("Content-type: ".$type);
                        header('Content-Length: '.$row['filesize']);
                        //if ($type == 'application/octet-stream')
                        //	header('Content-Disposition: attachment; filename='.$row['filename']);
                        //else
                        header("Content-Disposition: inline");
                        $displaying_file = company_path(). "/project_images/".$row['unique_name'];
                        echo file_get_contents($displaying_file);
                        exit();
		}
	}	
}

function delete_selected_project_gallery_image(&$Mode, &$selected_id)
{
        $row = get_project_gallery_image($selected_id);
	$dir =  company_path()."/attachments";
	if (file_exists($dir."/".$row['unique_name'])){
		unlink($dir."/".$row['unique_name']);
        }
	delete_project_gallery_image($selected_id);	
	display_notification(_("Attachment has been deleted.")); 
	$Mode = 'RESET';
        
}