<?php

include("dbconnect.php");

session_start();
$session_id = $_COOKIE['srno'];


if (isset($_REQUEST['cartdetail'])) {

    $decodes = json_decode($_REQUEST['cartdetail'], true);
    $count = count($decodes);
    $num_vouchs = "";

    $email = $_REQUEST['email'];
    mysqli_query($conn,"DELETE FROM `cart` WHERE `email`='$email'") or die(mysqli_error($conn));

    for ($i = 0; $i < $count; $i++) {
        $code = $decodes[$i]['code'];
        $size = $decodes[$i]['size'];
        $qty = $decodes[$i]['qty'];
//        $rate = $decodes[$i]['rate'];

        $gprod = mysqli_query($conn,"SELECT * FROM `product` where code='$code' ") or die(mysqli_error($conn));
        $fprod = mysqli_fetch_object($gprod);

        $name = $fprod->dname;

        if ($fprod->cost2 == '') {
            $cost = $fprod->cost;
        } else {
            $cost = $fprod->cost2;
        }

        if ($session_id != "") {
            $guser = mysqli_query($conn,"SELECT * FROM `site_passmain` where srno='$session_id' ") or die(mysqli_error($conn));
            $fuser = mysqli_fetch_object($guser);
            $userid = $fuser->srno;
        } else {
            $userid = "";
        }



        mysqli_query($conn,"LOCK TABLES `cart`");
        
        $gen1 = mysqli_query($conn,"SELECT MAX(srl) AS maxcode FROM `cart` where srl != ''  LIMIT 0,1 ") or die(mysqli_error($conn));
        if (mysqli_num_rows($gen1) > 0) {
            $vvouch = mysqli_fetch_assoc($gen1);
            $qvouch = $vvouch["maxcode"] + 1;
        } else {
            $qvouch = '1';
        }
        $amount = $qty * $cost;
        mysqli_query($conn,"INSERT INTO `cart`(`srl`,`user`,`qty`,`code`,`name`,`cost`,`size`,`amount`,`email`)
                            VALUES ('$qvouch','$userid','$qty', '$code',N'$name', '$cost','$size','$amount','$email')");
        
        mysqli_query($conn,"UNLOCK TABLES");
    }
    echo $email;
}

