<?php

/**
 * Evaluating, preparing and uploading product images to the database
 *
 * @author Kaspars Daugulis <kaspars.daugulis@mtcmedia.co.uk>
 * @author Vladislavs Ignatjevs <vladislavs.ignatjevs@mtcmedia.co.uk>
 *
 */

use Mtc\Shop\Item\Image;

$noauth = true;
$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

init_request_values([
    'id' => null,
]);

$item_id = $_REQUEST['id'];

if ($filedata = upload_image('userfile', $image_folders['product_folders'], clean_page($_REQUEST['item_id']))) {
    $filename = clean_page($filedata['name']);


    $images = Image::query()
        ->where('item_id', '=', $_REQUEST['item_id'])
        ->get();

    $default = $images->count() == 0 ? 1 : 0;

    /*
     * grab the large images
     * get the height
     */

    $image_large = SITE_PATH . '/uploads/images/products/large/' . $filename;

    list($widthL, $heightL) = getimagesize($image_large);

    /*
     * grab the very large images
     * get the height
     */

    $image_VL = SITE_PATH . '/uploads/images/products/verylarge/' . $filename;

    list($widthVL, $heightVL) = getimagesize($image_VL);

    // if the very large height is less than or equal to large image then run the below
    if ($heightVL <= $heightL) {
        $zoom = 0;
    } else {
        $zoom = 1;
    }

    if ($images->count() < IMAGES_MAX) {

        foreach ($images as $image) {
            $image->order++;
            $image->save();
        }

        $newImage = Image::query()
            ->create([
                'item_id' => $_REQUEST['item_id'],
                'name' => $filename,
                'default' => $default,
                'zoom' => $zoom,
            ]);

        $data = [
            'id'      => $newImage->id,
            'default' => $default,
            'zoom'    => $zoom,
            'name'    => $filename,
            'alt'     => null,
            'hover'   => null,
            'small'   => null,
        ];
        $item_id = clean_page($_REQUEST['item_id']);

        require_once '../../../shop/admin/products/templates/image_table_row.php';
        ?>

        <input type="hidden" id="orderbytable" value="items_images"/>
        <input type="hidden" id="orderbyfield" value="order"/>

        <?php
    }
}
