<?php
session_start();
include 'includes/connect.php';

header('Content-Type: application/json');

$user_id = $_SESSION['user_id'] ?? $_SESSION['distributor_id'] ?? 0;

if($user_id == 0){
    echo json_encode(["success"=>false,"message"=>"Login required"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);

$brand = mysqli_real_escape_string($conn, $data['brand']);
$variety_id = intval($data['variety_id']);
$batch_id = intval($data['batch_id']); // ✅ NEW FIELD

if(empty($brand) || empty($variety_id) || empty($batch_id)){
    echo json_encode(["success"=>false,"message"=>"Invalid data"]);
    exit;
}

/* CHECK EXISTING */
$check = mysqli_query($conn, "
SELECT * FROM cart 
WHERE user_id='$user_id'
AND brand='$brand'
AND variety_id='$variety_id'
AND batch_id='$batch_id'
");

if(mysqli_num_rows($check) > 0){

    mysqli_query($conn,"
        UPDATE cart 
        SET quantity = quantity + 1
        WHERE user_id='$user_id'
        AND brand='$brand'
        AND variety_id='$variety_id'
        AND batch_id='$batch_id'
    ");

} else {

    mysqli_query($conn,"
        INSERT INTO cart (user_id, brand, variety_id, batch_id, quantity)
        VALUES ('$user_id','$brand','$variety_id','$batch_id',1)
    ");
}

echo json_encode([
    "success"=>true,
    "message"=>"Added to cart with batch"
]);