<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);

$db = $GLOBALS['db'];
global $app_list_strings;

if (!isset($_GET['ajaxAction'])) {

    if (isset($_GET['date_from'])) {
        $dateFrom = date("Y-m-d", strtotime($_GET['date_from']));
    } else {
        $dateFrom = date("Y-m-d");
    }

    if (isset($_GET['date_to'])) {
        $dateTo = date("Y-m-d", strtotime($_GET['date_to']));
    } else {
        $dateTo = date("Y-m-d", strtotime("+ 1 month"));
    }

    $query = "SELECT s.id as orderId, s.document_no, s.status, s.parent_name, s.parent_id, s.send_date, s.type,
                     p.code, p.name, ps.ecmproduct_id, ps.description,
                     si.quantity, p.vendor_part_no as kind, p.brand, p.part_no as size, p.shape,
                     ss.quantity as stockState, si.id as item_id, s.shipping_address_name, ps.production_date,
                     ps.quantity as scheduledQuantity, ps.id as id
                FROM productionScheduler AS ps
                LEFT JOIN ecmsaleitems AS si
                ON ps.ecmsaleitem_id = si.id
                LEFT JOIN ecmsales AS s
                ON ps.ecmsale_id = s.id
                INNER JOIN ecmproducts AS p
                ON ps.ecmproduct_id = p.id
                LEFT JOIN ecmstockstates AS ss
                ON ss.product_id = ps.ecmproduct_id AND ss.stock_id = 'c7afd71a-4c3a-bde4-138d-4acaee1644e4'
                WHERE ps.deleted = 0 AND 
                    (
                        (ps.production_date >= '$dateFrom' AND ps.production_date <= '$dateTo') 
                        OR ps.production_date IS NULL OR ps.production_date = '0000-00-00')
                ORDER BY s.delivery_date, s.register_date, s.document_no";

    //echo $query;

    $rows = $db->query($query);
    $data = array();
    $i = 0;
    while ($r = $db->fetchByAssoc($rows)) {
        $row = array();
        $i++;
        $row['position'] = $i;
        $row['id'] = $r['id'];
        $row['productName'] = strlen($r['name']) > 55 ? substr($r['name'], 0, 55) . "..." : $r['name'];
        $row['productFullName'] = $r['name'];
        $row['productCode'] = strlen($r['code']) > 20 ? substr($r['code'], 0, 20) . "..." : $r['code'];
        $row['productFullCode'] = $r['code'];
        $row['productId'] = $r['ecmproduct_id'];
        $row['productQty'] = $r['quantity'];
        $row['qty'] = $r['scheduledQuantity'];
        $row['productKind'] = $r['kind'];
        $row['productSize'] = $r['size'];
        $row['productShape'] = $app_list_strings['ecmproducts_shape_dom'][$r['shape']];
        $row['productBrand'] = $app_list_strings['ecmproducts_brand_dom'][$r['brand']];
        $row['orderNo'] = $r['document_no'];
        $row['orderId'] = $r['orderId'];
        $row['orderStatus'] = $app_list_strings['ecmsales_status_dom'][$r['status']];
        $row['orderType'] = $app_list_strings['ecmsales_type_dom'][$r['type']];
        $row['orderParent'] = $r['parent_name'];
        $row['orderParentId'] = $r['parent_id'];
        $row['orderSendDate'] = $r['send_date'];
        $row['orderItemId'] = $r['item_id'];
        $row['description'] = strlen($r['description']) > 0 ? substr($r['description'], 0, 30) : '';
        $row['fullDescription'] = $r['description'];
        $row['shippingTo'] = ($r['shipping_address_name'] == 'Adres korespondencyjny' ? '' : $r['shipping_address_name']);
        $row['productionDate'] = $r['production_date'] == '0000-00-00' ? '' : $r['production_date'];
        $row['productStockState'] = $r['stockState'] | 0;

        $data[] = $row;
    }

    $smarty = new Sugar_Smarty();
    $smarty->assign("data", $data);
    $smarty->assign("dateFrom", $GLOBALS['timedate']->to_display_date($dateFrom));
    $smarty->assign("dateTo", $GLOBALS['timedate']->to_display_date($dateTo));
    echo $smarty->display('modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl');
} else {
    switch ($_GET['ajaxAction']) {
        case 'saveQty':
            saveQty($_GET['id'], $_GET['qty']);
            break;
        case 'duplicatePositions':
            duplicatePositions($_GET['ids']);
            break;
        case 'removePositions':
            removePositions($_GET['ids']);
            break;
        case 'saveProductionDate':
            saveProductionDate($_GET['id'], $_GET['date']);
            break;
        case 'saveProductDescription':
            saveProductDescription($_GET['id'], $_GET['description']);
            break;
        case 'exportExcel':
            exportExcel();
            break;
    }
}

function saveQty($id, $qty)
{
    $db = $GLOBALS['db'];
    $query = sprintf("UPDATE productionScheduler SET quantity='%d' WHERE id='%s'", $qty, $id);
    $db->query($query);
}

function duplicatePositions($ids)
{
    $db = $GLOBALS['db'];
    global $current_user;
    $ids = explode("|", $ids);
    foreach ($ids as $id) {
        $res = $db->fetchByAssoc($db->query("SELECT * FROM productionScheduler WHERE id ='$id'"));
        $query = sprintf("INSERT INTO productionScheduler VALUES ('%s', '%s', '%s', '%d', NOW(), NOW(), '%s', '%s', 0, '%s', '%d', '%s', '%s');",
            generateUuidV4(), $res['ecmsaleitem_id'], $res['ecmsale_id'], $res['quantity'], $current_user->id, $current_user->id, $res['ecmproduct_id'],
            $res['is_component'], $res['production_date'], $res['description']);
        $db->query($query);
    }
}

function removePositions($ids)
{
    $db = $GLOBALS['db'];
    global $current_user;
    $ids = explode("|", $ids);
    $query = sprintf("UPDATE productionScheduler SET deleted=1, modified_user_id='%s', date_modified=NOW() WHERE id IN ('%s')",
        $current_user->id, join("','", $ids));
    $db->query($query);
}
function saveProductionDate($id, $date)
{
    $db = $GLOBALS['db'];
    $date = date("Y-m-d", strtotime($date));
    if ($date == '1970-01-01') {
        $db->query("UPDATE productionScheduler SET production_date=NULL WHERE id='$id'");
    } else {
        $db->query("UPDATE productionScheduler SET production_date='$date' WHERE id='$id'");
    }
}
function saveProductDescription($id, $description)
{
    $db = $GLOBALS['db'];
    $description = mysql_escape_string($description);
    $db->query("UPDATE productionScheduler SET description='$description' WHERE id='$id'");
    echo "UPDATE productionScheduler SET description='$description' WHERE id='$id'";
}
function exportExcel() {
    echo 'bhhh';
    require_once  'modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php';
    echo 'qqqqqq';
    $books = [
        ['ISBN', 'title', 'author', 'publisher', 'ctry' ],
        [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'],
        [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
    ];
    echo 'a';
    $xlsx = Shuchkin\SimpleXLSXGen::fromArray( $books );
    echo json_encode($xlsx);
    $xlsx->saveAs('books.xlsx');
    echo 'done';
}
function generateUuidV4()
{
    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}