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

$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);

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

        session_start();
        $_SESSION['error'] = 'You do not have permission to create selection items';

        header('Location: '.URL_APP_ADMIN);
        exit;
    }
}

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

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

    header('Location: '.URL_APP_ADMIN);
    exit;
}

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

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

    header('Location: '.URL_APP_ADMIN);
    exit;
}

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

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

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.new-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.new-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);
            session_start();
            $_SESSION['error'] = 'There was an error with your file upload';
            exit;
        }
    }
} elseif ( $_POST['selectionItemImageUrl'] ) {
    $filename = $now.'.jpg';
    $image = file_get_contents($_POST['selectionItemImageUrl']);
    if ( !file_put_contents(PATH_SELECTION_ATTACHMENTS.'/'.$filename, $image) ) {

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

        session_start();
        $_SESSION['error'] = 'There was an error saving the selection image. Try again';

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

$selection = [
    'projectId' => $_POST['projectId'],
    'groupId' => $_POST['groupId'],
    'title' => $_POST['title'],
    'vendor' => $_POST['vendor'],
    'description' => $_POST['description'],
    'link' => $_POST['link'],
    'image' => $filename,
    'cost' => $_POST['cost'],
    'unit' => $_POST['unit'],
    'quantity' => $quantity
];

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

$db->insert('selection_item', $selection);
$txt .= "selection created\n";

$newSelection = $db->row("SELECT * FROM selection_item WHERE projectId = ? AND groupId = ? AND title = ? AND description = ?", $_POST['projectId'], $_POST['groupId'], $_POST['title'], $_POST['description']);
$txt .= "new selection id: ".$newSelection['id']."\n";
foreach ( $_POST['tags'] as $tag ) {
    $db->insert('selection_item_tag', ['selectionItemId' => $newSelection['id'], 'tagId' => $tag]);
    $txt .= "inserted tag: $tag\n";
}

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

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

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