<?php 
ob_start();
session_start();
include "../config/config.php";
include "../config/session.php";



if(isset($_POST['type']) && $_POST['type']=='create_barcode'){
     try{
         
         $pdo->beginTransaction(); 
         
        // Details Here
        $purchase_id = $_POST['purchase_id'];
        $per_stone_amount = $_POST['per_stone_amount'];
        $total_cross_weight = $_POST['total_cross_weight'];
        $total_stone_weight = $_POST['total_stone_weight'];
        $total_net_weight = $_POST['total_net_weight'];
         
        $total_c_wt=0;
        $total_s_wt=0;
        $total_n_wt=0;
        
        
        for($p=0;$p<count($_POST['product_id']);$p++){
    	            $cross_weight = $_POST['cross_weight'][$p];
                    $stone_weight = $_POST['stone_weight'][$p];
                    $net_weight = $_POST['net_weight'][$p];
                    
                    $total_c_wt+=$cross_weight;
                    $total_s_wt+=$stone_weight;
                    $total_n_wt+=$net_weight;
                    
    	}
    	
    	
    	if($total_cross_weight<$total_c_wt || $total_stone_weight<$total_s_wt || $total_net_weight<$total_n_wt){
    	    error_log("Purchase ID: TOTAL CROSS weight IS EQUAL GREATR: ".$purchase_id);
    	    $return_arr['status']=400;
            $return_arr['error'] = true;
            $return_arr['message'] = "Barcode Generation is Failed!";
            print_r(json_encode($return_arr));
            return false;
            exit(); 
    	}
    	    
    	    
    	    
    	    
    	    
        for($r=0;$r<count($_POST['product_id']);$r++){
            
            $product_id = $_POST['product_id'][$r];
            
            
            $statements_purchase_items = $pdo->prepare("SELECT pi.*,
                p.gst_amount
                FROM `tbl_purchases_items` pi 
                LEFT JOIN tbl_purchases p ON p.id=pi.purchase_id
                WHERE pi.id=?");
            $statements_purchase_items->execute(array($product_id));
            $purchase_items_results = $statements_purchase_items->fetchAll(PDO::FETCH_ASSOC);
            $purchase_items_totalDatas = $statements_purchase_items->rowCount();
            
            if($purchase_items_totalDatas>0){
                $purchase_making_charges = $purchase_items_results[0]['making_charges'];
                $purchase_gst_amount = $purchase_items_results[0]['gst_amount'];
            }

                    
                    $purchase_order_items_id = $_POST['purchase_order_items_id'][$r];
                    $product_ids = $_POST['product_ids'][$r];
                    $product_name = $_POST['product_name'][$r];
                    $category = $_POST['category'][$r];
                    $sub_category = $_POST['sub_category_name'][$r];
                    
                    $unit = $_POST['unit'][$r];
                    $cross_weight = $_POST['cross_weight'][$r];
                    $stone_weight = $_POST['stone_weight'][$r];
                    $net_weight = $_POST['net_weight'][$r];
                    $stone_cost = $_POST['stone_cost'][$r];
                    $purity = $_POST['purity'][$r];
                    $wastage = $_POST['wastage'][$r];
                    $others_weight = $_POST['tag_weight'][$r];
                    $size = isset($_POST['size'][$r]) ? $_POST['size'][$r]:0;
                    $stone_name = isset($_POST['stone_name'][$r]) ? $_POST['stone_name'][$r]:0;
                    $stone_purity = isset($_POST['stone_purity'][$r]) ? $_POST['stone_purity'][$r]:0;
                    $per_gram_amount = isset($_POST['per_gram_amount'][$r]) ? $_POST['per_gram_amount'][$r]:0;
                    
                    
                    $gst_per_gm = $purchase_gst_amount/$net_weight;
                    $gst_price = $gst_per_gm*$net_weight;
                    
                        $making_charges = $purchase_making_charges/$net_weight;
                        $making_charges_price = $making_charges*$net_weight;
                    
                    
                    $purchase_price = ($per_gram_amount*$net_weight)+($stone_weight*$per_stone_amount)+$making_charges_price+$gst_price;
                    
                    
                    
                    error_log("------ Starts -------");
                    error_log("Purchase Items ID: ".$purchase_order_items_id);
                    error_log("Net Weight: ".$net_weight);
                    error_log("Per Gram Amount: ".$per_gram_amount);
                    error_log("Stone Weight: ".$stone_weight);
                    error_log("Per Stone Amount: ".$per_stone_amount);
                    error_log("Purchase Price: ".$purchase_price);
                    error_log("------ Endsss -------");
                    
                    
                    
                    
                    $barcode_items_id = $_POST['barcode_items_id'][$r];
                    if($stone_weight==0 || $stone_weight==""){
                        $product_type = 1;
                    }else{
                        $product_type = 2;
                    }
                    $update_status = 1;
                    
                    
                    
        $statementsss = $pdo->prepare("SELECT * FROM `tbl_products_name` WHERE id=?");
        $statementsss->execute(array($product_name));
        $resultsss = $statementsss->fetchAll(PDO::FETCH_ASSOC);
        $totalsss = $statementsss->rowCount();  
        if($totalsss>0){
            $quantity = $resultsss[0]['quantity'];
        }
                    
                    
                    
                    // Barcode Unique ID Starts Here
                    
                    
                    // 1) Main Product Name
                    // 2) Product Name
                    // 3) Category
                    // 4) Sub Category
                    // 5) Sub Typess
                    // 6) Product Type
                    // 7) Product HSN
                    
// 2) Product Name - HSN Starts Here
$statementss_1 = $pdo->prepare("SELECT product_hsn_code FROM `tbl_products_name` p WHERE p.id=?");
$statementss_1->execute(array($product_name));
$resultss_1 = $statementss_1->fetchAll(PDO::FETCH_ASSOC);
$totalDatas_1 = $statementss_1->rowCount();
if($totalDatas_1>0){
    $uni_1 = strtoupper(substr($resultss_1[0]['product_hsn_code'], 0, 2));
}else{
    $uni_1 = "";
}


// 3) Category - Starts Here
$statementss_3 = $pdo->prepare("SELECT category_hsn_code FROM `tbl_category` p WHERE p.id=?");
$statementss_3->execute(array($category));
$resultss_3 = $statementss_3->fetchAll(PDO::FETCH_ASSOC);
$totalDatas_3 = $statementss_3->rowCount();
if($totalDatas_3>0){
    $uni_3 = strtoupper(substr($resultss_3[0]['category_hsn_code'], 0, 2));
}else{
    $uni_3 = "";
}

// 4) Sub - Category - Starts Here
$statementss_4 = $pdo->prepare("SELECT sub_category_hsn_code FROM `tbl_sub_category` p WHERE p.id=?");
$statementss_4->execute(array($sub_category));
$resultss_4 = $statementss_4->fetchAll(PDO::FETCH_ASSOC);
$totalDatas_4 = $statementss_4->rowCount();
if($totalDatas_4>0){
    $uni_4 = strtoupper(substr($resultss_4[0]['sub_category_hsn_code'], 0, 2));
}else{
    $uni_4 = "";
}
                    
                    $barcode_unique_id = $uni_1.$uni_3.$uni_4;
                    // Barcode Unique ID Endsss Here
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    if($barcode_items_id!=0){
                        
                        
                        $statement_purchase_items = $pdo->prepare("UPDATE `tbl_barcode_items` SET `barcode_id`=?, `product_name`=?, `category`=?, `type`=?, `unit`=?,
                                `cross_weight`=?, `stone_weight`=?, `net_weight`=?, `stone_cost`=?, 
                                `purity`=?, `created_by`=?, `purchase_items_id`=?, `pro_ids`=?, 
                                `wastage`=?, `others_weight`=?, `quantity`=?, `size`=? WHERE id=?");
                                
                        $statement_purchase_items_result = $statement_purchase_items->execute(array($purchase_id, $product_name, $category, $product_type, $unit, 
                                $cross_weight, $stone_weight, $net_weight, $stone_cost, 
                                $purity, $session_id, $purchase_order_items_id, $product_ids, 
                                $wastage, $others_weight, $quantity, $size, $barcode_items_id)); 
                        
                        
                        
                            $statement = $pdo->prepare("UPDATE `tbl_product_variants` SET `product_name`=?, `category`=?, `sub_category`=?, `cross_weight`=?, `purchase_price`=?, 
                                        `selling_price`=?, `quantity`=?,  `purity`=?, `unit`=?, 
                                        `stone_weight`=?, `stone_cost`=?, `type`=?, `wastage`=?, `others_weight`=?, 
                                        `updated_by`=?,  `pro_ids`=?, `net_weight`=?, `barcode_items_id`=? WHERE barcode_items_id=?");
                                      
                            $result = $statement->execute(array($product_name, $category, $sub_category, $cross_weight, $purchase_price, 
                                    	$selling_price, $quantity, $purity, $unit, 
                                    	$stone_weight, $stone_cost, $product_type, $wastage, $tags_label_weight,
                                    	$session_id,  $product_ids, $net_weight, $barcode_items_id, $barcode_items_id));
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        
                    }else{
                        
                        
                        // Purchase Quantity - Here
                        $statementss_qty = $pdo->prepare("SELECT * FROM `tbl_products_name` p WHERE p.id=?");
                        $statementss_qty->execute(array($product_name));
                        $resultss_qty = $statementss_qty->fetchAll(PDO::FETCH_ASSOC);
                        $totalDatas_qty = $statementss_qty->rowCount();
                        if($totalDatas_qty>0){
                            $pro_quantity = $resultss_qty[0]['quantity'];
                        }
                        
                        
            
            
                                
                                
                        $statement_purchase_items = $pdo->prepare("INSERT INTO `tbl_barcode_items` ( `barcode_id`, `product_name`, `category`, `type`, `unit`,
                                `cross_weight`, `stone_weight`, `net_weight`, `stone_cost`, `purity`, 
                                `created_by`, `purchase_items_id`, `pro_ids`, `wastage`, `others_weight`, 
                                `quantity`, `stone_name`, `stone_purity`, `barcode_unique_id`,
                                `size`, `per_stone_amount`, `per_gram_amount`, `purchase_price`, `sub_category`, `making_charges`) VALUES (?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,?,
                                ?,?,?,?,
                                ?,?,?,?,?,?)");
                        $statement_purchase_items_result = $statement_purchase_items->execute(array($purchase_id, $product_name, $category, $product_type, $unit, 
                                $cross_weight, $stone_weight, $net_weight, $stone_cost, $purity, 
                                $session_id, $purchase_order_items_id, $product_ids, $wastage, $others_weight, 
                                $pro_quantity, $stone_name, $stone_purity, $barcode_unique_id,
                                $size, $per_stone_amount, $per_gram_amount, $purchase_price, $sub_category, $making_charges_price)); 
                                
                                
                        
                                
                        $barcode_items_id = $pdo->lastInsertId();
                        
                        
                        
            // Product HSN Starts Here 
            $pro_hsn="10000";
    	    $statement = $pdo->prepare("SHOW TABLE STATUS WHERE `name` = 'tbl_products'");
            $statement->execute();
            $products_results = $statement->fetchAll(PDO::FETCH_ASSOC); 
            foreach ($products_results as $pro) {
    	        $pro_hsn = $pro_hsn + $pro['Auto_increment'];
            } 
            // Product HSN Endsss Here 
            
            
            $product_hsn = $pro_hsn;
            
            // Amount - Here
            $selling_price = 0;
            
            
            
                        $statement = $pdo->prepare("INSERT INTO `tbl_products`(`product_name`, `category`, `sub_category`, `type`, `product_hsn`, `created_by`, `barcode_items_id`) VALUES (?,?,?,?,?,?,?)");
                        $result = $statement->execute(array($product_name, $category, $sub_category, $product_type, $product_hsn, $session_id, $barcode_items_id));
                        
                        if($result){
                            
            $product_id = $pdo->lastInsertId();
            
            // Product HSN Starts Here 
            $pro_hsn="10000";
    	    $statement = $pdo->prepare("SHOW TABLE STATUS WHERE `name` = 'tbl_product_variants'");
            $statement->execute();
            $products_results = $statement->fetchAll(PDO::FETCH_ASSOC); 
            foreach ($products_results as $pro) {
    	        $pro_hsn = $pro_hsn + $pro['Auto_increment'];
            } 
            // Product HSN Endsss Here 
            $hsn_code = $pro_hsn;
            
            
            
                            $statement = $pdo->prepare("INSERT INTO `tbl_product_variants`(`product_id`, `pro_ids`, `product_name`, `category`, `sub_category`, 
                            `barcode_items_id`, `barcode_unique_id`, `purchase_items_id`, `hsn_code`, `type`, 
                            `unit`, `cross_weight`, `stone_weight`, `net_weight`, `stone_cost`, 
                            `stone_name`, `stone_purity`, `quantity`, `purchase_quantity`, `purity`, 
                            `wastage`, `others_weight`, `purchase_price`, `selling_price`, `per_gram_amount`, 
                            `per_stone_amount`, `created_by`, `making_charges`) VALUES (?,?,?,?,?,
                                        ?,?,?,?,?,
                                        ?,?,?,?,?,
                                        ?,?,?,?,?,
                                        ?,?,?,?,?,
                                        ?,?,?)");
                                      
                            $result = $statement->execute(array($product_id, $product_ids, $product_name, $category, $sub_category, 
                                $barcode_items_id, $barcode_unique_id, $purchase_order_items_id, $hsn_code, $product_type,
                                $unit, $cross_weight, $stone_weight, $net_weight, $stone_cost,
                                $stone_name, $stone_purity, $pro_quantity, $pro_quantity, $purity,
                                $wastage, $others_weight, $purchase_price, $selling_price, $per_gram_amount,
                                $per_stone_amount, $session_id, $making_charges_price));
                        }
                        
                    }
        }
        
         
 
         
    
        if($result){    
            $pdo->commit();
            $return_arr['message']='Barcode Successfully Created...';
            $return_arr['status']=200;
        } 
        else{
            $return_arr['message']='Something Went Wrong..';
            $return_arr['status']=400;
        }
    }catch(PDOException $e){
        $pdo->rollBack();
        error_log($e);
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}



?>