<?php

class ImportController {
	public static function downloads() {
		return blade("downloads");
	}

	public static function imports() {
		return blade("imports");
	}

	public static function api_imports() {
		$is = ProcessJob::find([["imported", "=", 0]])->orderBy("queued")->limit(50)->all();
		foreach ($is as $i) {
			$i->load("revision");
		}
		return $is;
	}

	public static function api_delete_import($id) {
		$d = new ProcessJob($id);
		if ($d->valid()) {
			$d->delete();
		}
		return ImportController::api_imports();
	}

	public static function api_set_import($_request, $id) {
		$d = new ProcessJob($id);
		if ($d->valid()) {
			foreach ($_POST as $k=>$v) {
				$d->$k = $v;
			}
			$d->save();
		}
		return ImportController::api_imports();
	}

	public static function api_add_document($_request, $id) {

		$job = new ProcessJob($id);

		$doc = Document::find([["internal_id", "=", $_request->put('internal_id')]])->first();
		if (!$doc) {
			$doc = new Document;
			$doc->internal_id = trim($_request->put('internal_id'));
			$doc->title = trim($_request->put('title'));
			$doc->subtitle = trim($_request->put('subtitle'));
			$doc->subsubtitle = trim($_request->put('subsubtitle'));
			$doc->overview = trim($_request->put('overview'));
			$doc->owner = get_user()->id;
			$doc->save();
			
			$prods = explode(",", $_request->put('products'));
			foreach ($prods as $product) {
				$dp = new DocProduct;
				$dp->document = $doc->id;
				$dp->product = $product;
				$dp->save();
			}
		}

		$job->document = $doc->id;

		$rev = new Revision($job->revision);
		$rev->document = $doc->id;
		$rev->revno = trim($_request->put('revno'));
		$rev->month = $_request->put('month');
		$rev->year = $_request->put('year');
		$rev->owner = get_user()->id;
		$rev->save();

		$job->imported = time();
		$job->save();

		return ImportController::api_imports();
	}
}
