<?php
session_start();
require_once 'db_connection.php';

date_default_timezone_set('Asia/Colombo');
$currentDate = date('Y-m-d H:i:s');

// Get inputs
$searchbarcode = $_POST['searchbarcode'] ?? '';
$user_id = $_SESSION['user_id'] ?? 0;
$branch_id = $_SESSION['branch_id'] ?? 0;

if (!$searchbarcode || !$user_id || !$branch_id) {
    echo json_encode(['error' => 'Missing required data.']);
    exit;
}

// Determine itemcode and quantity
$firstPart = $searchbarcode;
$searchQty = 1;
$searchQtyDefault = 1;

if (strlen($searchbarcode) == 10) {
    $firstPart = substr($searchbarcode, 0, 5);
    $secondPart = substr($searchbarcode, 5);

    // Optimized: Only check category if 10-digit barcode
    $categoryResult = mysqli_query($conn, "SELECT category FROM mobileproducts WHERE itemcode = '$firstPart' LIMIT 1");
    if ($categoryRow = mysqli_fetch_assoc($categoryResult)) {
        $searchQty = ($categoryRow['category'] == 19) 
            ? floatval(substr($secondPart, 0, 2) . "." . substr($secondPart, 2)) 
            : 1;
    }
}

// Single optimized query
$sql = "
    SELECT 
        mp.prid, mp.proname, mp.discount1, mp.discount_type1,
        mp.sellprice, mp.price AS costprice, mp.itemcode, 
        IFNULL(ts.qty, 0) AS stock_qty
    FROM mobileproducts mp
    LEFT JOIN tbl_stock ts ON ts.prid = mp.prid AND ts.branch_id = '$branch_id'
    WHERE (mp.itemcode = '$firstPart' OR mp.itemcode = '$searchbarcode') AND mp.status = 1
    LIMIT 1
";

$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();

    $prid = $row['prid'];
    $proname = $row['proname'];
    $pro_dis = $row['discount1'];
    $discount_type = $row['discount_type1'];
    $price = $row['sellprice'];
    $costprice = $row['costprice'];
    $itemcode = $row['itemcode'];
    $stock_qty = $row['stock_qty'];
    
    // Format discount based on type
    $dis = ($discount_type == 1) ? $pro_dis . "%" : $pro_dis;

    // Check if item already in cart
    $checkCart = $conn->query("
        SELECT * FROM mobiletemporarycart
        WHERE proid = '$prid' AND pro_dis = '$pro_dis' 
        AND branch_id = '$branch_id' AND user_id = '$user_id' 
        AND orderid = 0 AND hold = 0
    ");

    if ($checkCart && $checkCart->num_rows > 0) {
        // Update quantity
        $update = $conn->query("
            UPDATE mobiletemporarycart 
            SET pro_qty = pro_qty + $searchQtyDefault
            WHERE proid = '$prid' AND pro_dis = '$pro_dis' 
            AND branch_id = '$branch_id' AND user_id = '$user_id' 
            AND orderid = 0 AND hold = 0
        ");
        if ($update) {
            echo json_encode([$prid, $stock_qty, $proname, $price, $prid, $dis, $costprice, $itemcode]);
        } else {
            echo json_encode(['error' => 'Failed to update cart.']);
        }
    } else {
        // Insert new item to cart
        $insert = $conn->query("
            INSERT INTO mobiletemporarycart (
                orderid, proid, pro_price, pro_dis, pro_qty, user_id, 
                return_qty, return_date, return_user, hold, branch_id
            ) VALUES (
                0, '$prid', '$price', '$pro_dis', '$searchQtyDefault', '$user_id',
                0, '$currentDate', 0, 0, '$branch_id'
            )
        ");
        if ($insert) {
            $last_id = $conn->insert_id;
            echo json_encode([$last_id, $stock_qty, $proname, $price, $prid, $dis, $costprice, $itemcode, $searchQty]);
        } else {
            echo json_encode(['error' => 'Failed to add to cart.']);
        }
    }

} else {
    echo json_encode(['error' => 'Product not found or unavailable.']);
}
?>
