<?php

// Set defaults
$mode = "list";
$admin = false;

$admin_group = "sucsstaff";

// who's notified of items being requested?
$junk_contact = "admin@sucs.org";

$admin = isset($session->groups[$admin_group]);

// If you're an admin and the path ends in Edit/ then a number put it into edit mode
// create canedit rules
$canedit = isset($pathlist[($component[depth] / 2) + 1]);
$canedit = $canedit && isset($pathlist[($component[depth] / 2) + 2]);
$canedit = $canedit && $pathlist[($component[depth] / 2) + 1] == 'Edit';
$canedit = $canedit && is_numeric($pathlist[($component[depth] / 2) + 2]);
$canedit = $canedit && $admin;
// Apply canedit rules
if ($canedit) {
    $id = $pathlist[($component[depth] / 2) + 2];
    $items = $DB->GetAll("SELECT id, title, category, description, donated_by, status FROM inventory WHERE id=? AND requested_by IS NULL", $id);
    if (sizeof($items) === 1) {
        $item = $items[0];
        $smarty->assign("item", $item);
        $mode = "edit";
    }
}

// If you're an admin and the path ends in Add put it into add mode
// create canadd rules
$canadd = isset($pathlist[($component[depth] / 2) + 1]);
$canadd = $canadd && $pathlist[($component[depth] / 2) + 1] == 'Add';
$canadd = $canadd && $admin;
// Apply canadd rules
if ($canadd) {
    $mode = "add";
}


// Process actions before retrieving the data
// List request data
if ($session->loggedin && isset($_REQUEST['action'])) {
    // Junk Requests
    if ($_REQUEST['action'] == "Request") {
        // Request Item if its available
        $query = "UPDATE inventory SET requested_by=?, requested_on=now() WHERE id=? AND requested_by IS NULL";
        $DB->Query($query, array($session->username, $_REQUEST['item']));

        // mail someone so we know that this has been requested
        $iteminfo = $DB->GetRow("SELECT title, description FROM inventory WHERE id=?", array($_REQUEST['item']));
        $msgbody = "User {$session->username} has requested the junk item:\n\n";
        $msgbody .= "{$iteminfo['title']}: {$iteminfo['description']}\n\n";
        $msgbody .= "Please ensure this is taken away and never brought back.";
        mail($junk_contact, "Junk item requested", $msgbody);

    } elseif ($_REQUEST['action'] == "Un-Request") {
        // Un-Request Item
        if ($admin) {
            // if you're admin just do it
            $query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=?";
            $array = array($_REQUEST['item']);
        } else {
            // if not admin check if you requested it first
            $query = "UPDATE inventory SET requested_by=null, requested_on=null WHERE id=? AND requested_by=?";
            $array = array($_REQUEST['item'], $session->username);
        }
        $DB->Query($query, $array);
    } elseif ($_REQUEST['action'] == "Take" && $admin) {
        // Take item, if you're admin
        $query = "UPDATE inventory SET taken_on=now() WHERE id=? AND requested_by IS NOT NULL";
        $DB->Query($query, $_REQUEST['item']);
    } elseif ($_REQUEST['action'] == "Remove" && $admin) {
        // Remove item, if you're admin
        $query = "DELETE FROM inventory WHERE id=?";
        if ($DB->Query($query, $_REQUEST['item'])) {
            message_flash("Item removed");
        } else {
            trigger_error("Failed to remove item");
        }
    } elseif ($_REQUEST['action'] == "Not Junk" && $admin) {
        // Mark item as not junk if it's not been requested and you're admin
        $query = "UPDATE inventory SET status='unknown' WHERE id=? AND requested_by IS NULL";
        $DB->Query($query, $_REQUEST['item']);
    } elseif ($_REQUEST['action'] == "Junk" && $admin) {
        // Mark item as junk, if you're admin
        $query = "UPDATE inventory SET status='junk' WHERE id=?";
        $DB->Query($query, $_REQUEST['item']);
    }

}
// Update/Add item
if ($session->loggedin && $admin && (isset($_REQUEST['update']) || isset($_REQUEST['add']))) {
    // try to guess which category field the user meant us to see
    // ideally we'd use an html combo box, but since they don't exist...
    if ($_REQUEST['categorymenu'] == "") {
        $category = $_REQUEST['category'];
    } else {
        $category = $_REQUEST['categorymenu'];
    }

    // Update/Add item if title and category are filled in else error
    if ($_REQUEST['title'] != "" && $category != "") {
        // if the description is blank, return null
        if ($_REQUEST['description'] == "") {
            $description = null;
        } else {
            $description = $_REQUEST['description'];
        }
        // if the donated_by is blank, return null
        if ($_REQUEST['donated_by'] == "") {
            $donated_by = null;
        } else {
            $donated_by = $_REQUEST['donated_by'];
        }
        // run the query
        if (isset($_REQUEST['update'])) {
            $query = "UPDATE inventory SET title=?, category=?, description=?, donated_by=?, status=? WHERE id=?";
            $array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status'], $_REQUEST['id']);
            if ($DB->Query($query, $array)) {
                message_flash("Item Updated");
            } else {
                trigger_error("Item update failed :-(", E_USER_ERROR);
            }
        } elseif (isset($_REQUEST['add'])) {
            $query = "INSERT INTO inventory (title, category, description, donated_by, status) VALUES (?, ?, ?, ?, ?)";
            $array = array($_REQUEST['title'], $category, $description, $donated_by, $_REQUEST['status']);
            if ($DB->Query($query, $array)) {
                message_flash("Item Added");
            } else {
                trigger_error("Adding item failed :-( - " . $DB->ErrorMsg(), E_USER_ERROR);
            }
        }
    } else {
        trigger_error("Required field(s) missing", E_USER_WARNING);
    }
}

// Remove old taken junk
$DB->Query("DELETE FROM inventory WHERE (taken_on + interval'7 days')  < now()");


if ($mode == 'list') {
    // Get junk from database, and give admin the full list
    if ($admin == true) {
        $junk = $DB->GetAll("SELECT * FROM inventory ORDER BY category, title, id");
    } else {
        $junk = $DB->GetAll("SELECT * FROM inventory WHERE status = 'junk' ORDER BY category, title, id");
    }
    //
    // Check there is some junk
    if (sizeof($junk) < 1) {
        $mode = "nojunk";
    } else {

        // group the junk by status then by category
        foreach ($junk as $junkitem) {
            if ($junkitem['status'] != 'junk') {
                $status = "unknown";
            } else if ($junkitem['requested_by'] == null) {
                $status = "available";
            } else if ($junkitem['taken_on'] == null) {
                $status = "requested";
            } else {
                $status = "taken";
            }

            $sortedjunk[$status][$junkitem['category']][] = $junkitem;
        }
        $smarty->assign("junk", $sortedjunk);
    }


} else {
    $categories = $DB->GetCol("SELECT DISTINCT category FROM inventory ORDER BY category ASC");
    $smarty->assign("categories", $categories);
}
// Generate output

$smarty->assign("statuses", array("unknown", "in use", "wanted", "junk"));
$smarty->assign("componentpath", $baseurl . $component[path]);
$smarty->assign("mode", $mode);
$smarty->assign("admin", $admin);

$output = $smarty->fetch("junk.tpl");

$smarty->assign("title", "Junk List");
$smarty->assign("body", $output);

?>