<?php

require_once "config.php";
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $ckode = $_GET['ckode'];
        $inputQty = $_GET['qty'];

        $stmt = $conn->prepare("SELECT cKode, cNama, cSat, QtyMin, HargaPerPcs FROM vwqtyhargabarang WHERE cKode = ? ORDER BY QtyMin DESC"); 
        $stmt->bind_param("s", $ckode);
        $stmt->execute();

        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        
        $totalBarang = 0;

foreach ($data as $key => &$row) {
    $row['QtyMin'] = rtrim(rtrim($row['QtyMin'], '0'), '.');
    $row['HargaPerPcs'] = rtrim(rtrim($row['HargaPerPcs'], '0'), '.');

    $dapet = floor($inputQty / $row['QtyMin']);
    $row['dapet'] = $dapet;

    if ($dapet == 0) {
        unset($data[$key]); 
    } else {
        $inputQty -= $dapet * $row['QtyMin'];

        $hargaPerPcs = floatval($row['HargaPerPcs']);
        $row['total'] = $dapet * $hargaPerPcs;

        $totalBarang += $row['total'];
    }
}

        echo json_encode([
            "totalBarang" => $totalBarang
        ]);

        $stmt->close();
        break;

    default:
        echo json_encode(array("error" => "Unsupported request method."));
        break;
}

$conn->close();
?>
