<?php

require_once('db.php');

$records    =   array();
$sql = "SELECT * FROM data_mst ORDER BY 1";
$stmt = $db->prepare($sql); 
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) 
{
    $records[]   =  $row;
}


foreach($records as $k => $v)
{
    $sql = "SELECT * FROM category M WHERE LOWER(M.category_name) = LOWER(?)";
    $stmt = $db->prepare($sql);
    $stmt->bind_param("s", $v["product_category"]); 
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    if(($row))
    {
        $v["CATEGORY_ID"]   =   $row["id"];
    }
    else
    {
        $v["CATEGORY_ID"]   =   64;
    }

    $records[$k]    =   $v;
}


foreach($records as $k => $v)
{

    $sql = "    INSERT INTO product_mst(title, description, category_id, price, discount_price, product_status, quantity) 
                VALUES (?, '', ?, ?, '', 'D', ?)";
    $stmt = $db->prepare($sql); 
    $stmt->bind_param("ssss", $v["name"], $v["CATEGORY_ID"], $v["sales_price"], $v["quantity_on_hand"]); 
    $result     =   $stmt->execute();
    if(($result))
    {
        $v["PRODUCT_MST_ID"]    =   $db->insert_id;
    }
    $records[$k]    =   $v;
}


foreach($records as $k => $v)
{
    $imgname    = $v["PRODUCT_MST_ID"].".png";  
    $path       = "../uploads/products/".$imgname;
    $status     = file_put_contents($path,base64_decode($v["image_128"]));
    if(($status))
    {
        $v["IMAGE_NAME"]    =   $imgname;
    }
    else
    {
        $v["IMAGE_NAME"]    =   '';
    }
    $records[$k]    =   $v;
}


foreach($records as $k => $v)
{
    $sql = "    INSERT INTO product_images(product_mst_id, image_name, primary_image) 
                VALUES (?, ?, 'Y')";
    $stmt = $db->prepare($sql); 
    $stmt->bind_param("ss", $v["PRODUCT_MST_ID"], $v["IMAGE_NAME"]); 
    $result     =   $stmt->execute();
}


























































?>