<?php
// Set session cookie domain for your specific website
ini_set('session.cookie_domain', 'digitalcardwale.com');

require('connection.inc.php');
require('security.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Check login
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'login_required']);
    exit;
}

$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
$unit_id = isset($_POST['unit_id']) ? (int)$_POST['unit_id'] : 0;
$user_id = $_SESSION['user_id'];
$qty = isset($_POST['qty']) ? (int)$_POST['qty'] : 1;


if ($product_id > 0 && $unit_id > 0) {
    $check_sql = "SELECT id, quantity FROM cart WHERE user_id = ? AND product_id = ? AND unit_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param("iii", $user_id, $product_id, $unit_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $new_qty = $row['quantity'] + $qty;

        $update_sql = "UPDATE cart SET quantity = ? WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ii", $new_qty, $row['id']);
        $update_stmt->execute();
        $update_stmt->close();
    } else {
        $insert_sql = "INSERT INTO cart (user_id, product_id, unit_id, quantity) VALUES (?, ?, ?, ?)";
$insert_stmt = $conn->prepare($insert_sql);
$insert_stmt->bind_param("iiii", $user_id, $product_id, $unit_id, $qty);

        $insert_stmt->execute();
        $insert_stmt->close();
    }

    $stmt->close();
    echo json_encode(['status' => 'success']);
    exit;
}

echo json_encode(['status' => 'error']);

