<?php
$datetime = date("Y-m-d H:i:s");
$txt  = "\n$datetime - ".$_SERVER['PHP_SELF']."\n";
$txt .= "user:\n";
$txt .= print_r($user, true);
$txt .= "post:\n";
$txt .= print_r($_POST , true);
$txt .= "files:\n";
$txt .= print_r($_FILES , true);

$redirect = ( $user['superAdmin'] )
    ? URL_APP_ADMIN
    : URL_APP
;

if ( !isset($_POST['selectionItemId']) ) {
$txt .= "no selection item id\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

    session_start();
    $_SESSION['error'] = 'No selection item ID';

    header('Location: '.$redirect);
    exit;
}

if ( !$selection = $db->row("SELECT * FROM selection_item WHERE id = ?", $_POST['selectionItemId']) ) {
$txt .= "no selection by that id\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

    session_start();
    $_SESSION['error'] = 'Invalid selection item ID';

    header('Location: '.$redirect);
    exit;
}

$txt .= "selection item before update:\n";
$txt .= print_r($selection, true);

if ( !$user['superAdmin'] ) {
    if ( !$exists = $db->cell("SELECT id FROM client_project WHERE clientId = ? AND projectId = ?", $user['client']['id'], $selection['projectId']) ) {
$txt .= "user does not have permission to edit this selection item\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

        session_start();
        $_SESSION['error'] = 'You do not have permission to edit this selection item';

        header('Location: '.$redirect);
        exit;
    }
}

if ( !isset($_POST['title']) ) {
$txt .= "no title provided\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file); 

    session_start();
    $_SESSION['error'] = 'Selection item title is required';

    header('Location: '.$redirect);
    exit;
}

$quantity = ( !$_POST['quantity'] || $_POST['quantity'] < 1 || !is_numeric($_POST['quantity']) )
    ? 1
    : $_POST['quantity']
;

$now = strtotime(date('Y-m-d H:i:s'));

// echo "<pre>";
// print_r($_POST);
// echo "</pre>";

// echo "<pre>";
// print_r($_FILES);
// echo "</pre>";

// exit;

if ( !empty($_FILES) ) {
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    if ( $ext != 'JPG' && $ext != 'JPEG' && $ext != 'jpg' && $ext != 'jpeg' && $ext != 'PNG' && $ext != 'png' ) {
$txt .= "invalid file type uploaded\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

        session_start();
        $_SESSION['error'] = 'An upload had an invalid file type';
        exit;
    } else {
        $filename = "$now-".$_FILES['file']['name'];
        if ( !move_uploaded_file($_FILES['file']['tmp_name'], PATH_SELECTION_ATTACHMENTS.'/'.$filename) ) {
$txt .= "error moving uploaded file\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

            session_start();
            $_SESSION['error'] = 'There was an error with your file upload';
            exit;
        }
    }
} elseif ( $_POST['editSelectionItemFilename'] ) {
    $filename = $_POST['editSelectionItemFilename'];
} else {
    $filename = NULL;
}

$db->update('selection_item', [
    'title' => $_POST['title'],
    'vendor' => $_POST['vendor'],
    'description' => $_POST['description'],
    'link' => $_POST['link'],
    'image' => $filename,
    'cost' => $_POST['cost'],
    'unit' => $_POST['unit'],
    'quantity' => $quantity,
], ['id' => $selection['id']]);
$txt .= "selection item updated\n";

if ( $_POST['tags'] ) {
    $db->delete('selection_item_tag', ['selectionItemId' => $selection['id']]);
    foreach ( $_POST['tags'] as $tag ) {
        $db->insert('selection_item_tag', ['selectionItemId' => $selection['id'], 'tagId' => $tag]);
        $txt .= "inserted tag: $tag\n";
    }
}

$txt .= "done\n\n\n\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

session_start();
$_SESSION['error'] = 'Selection item updated';

if ( !isset($_POST['fromdz']) ) {
    header('Location: '.URL_APP.'/selections/?projectId='.$selection['projectId']);
}
exit;