<?php
class Document_log extends MY_Model
{
    const DB_TABLE = 'document_log';
    const DB_TABLE_PK = 'document_log_id';

    public function logChanges($old_document, $new_document, $user)
    {
    	$this->load->model("category");

    	$doc 				= new Document_log();
    	$doc->document_id 	= $new_document->document_id;
    	$doc->action_date 	= date("Y-m-d H:i:s");
    	$doc->action 		= $new_document->document_id . ': "' . ($old_document->title ? $old_document->title : $new_document->title) . "\"\n";

		if(!$old_document->document_id)
		{
			$doc->action .= "Created by " . $user->fname . " " . $user->lname . "\n";
		}
		else
		{
			$doc->action .= "Updated by " . $user->fname . " " . $user->lname . "\n";

			if($old_document->category_id != $new_document->category_id)
			{
				$old_category = new Category();
				$old_category->load($old_document->category_id);

				$category = new Category();
				$category->load($new_document->category_id);

				$doc->action .= "Category changed from " . $old_category->name . " to " . $category->name . " by " . $user->fname . " " . $user->lname . "\n";
			}

			if($old_document->access != $new_document->access)
			{
				$doc->action .= "Access changed from " . $old_document->access . " to " . $new_document->access . " by " . $user->fname . " " . $user->lname . "\n";
			}

			if($old_document->url != $new_document->url)
			{
				$doc->action .= "URL changed from " . $old_document->url . " to " . $new_document->url . " by " . $user->fname . " " . $user->lname . "\n";
			}

			if($old_document->published != $new_document->published)
			{
				if($new_document->published)
				{
					$doc->action .= "Published by " . $user->fname . " " . $user->lname . "\n";
				}
				else if(!$new_document->published)
				{
					$doc->action .= "Unpublished by " . $user->fname . " " . $user->lname . "\n";
				}
			}
		}

		$doc->action = trim($doc->action); // Remove trailing \n from the last line of the action.
		return $doc->save();
    }

    public function logDeleted($old_document, $user)
    {
    	$this->load->model("category");

    	$doc 				= new Document_log();
    	$doc->document_id 	= null;
    	$doc->action_date 	= date("Y-m-d H:i:s");
    	$doc->action 		= $old_document->document_id . ': "' . $old_document->title . "\"\n";
		$doc->action 		.= "Deleted by " . $user->fname . " " . $user->lname;
		return $doc->save();
    }
}
