<?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $cKodeMember = $_GET['cKodeMember'] ?? '';

    $query = $conn->prepare("SELECT 
                                cKodeMember,
                                CAST(SUM(nQty * nHarga) AS UNSIGNED) AS TotalHarga,
                                CAST(SUM(nSTotal) AS UNSIGNED) AS TotalSetelahDiskon,
                                CAST(SUM(nQty * nHarga) - SUM(nSTotal) AS UNSIGNED) AS TotalSelisih
                            FROM 
                                tbkeranjang
                            WHERE 
                                cKodeMember = ?
                            GROUP BY 
                                cKodeMember");

    $query->bind_param("s", $cKodeMember);

    if ($query->execute()) {
        $result = $query->get_result();
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();

            echo json_encode([
                'TotalHarga' => (int)$row['TotalHarga'],
                'TotalSetelahDiskon' => (int)$row['TotalSetelahDiskon'],
                'TotalSelisih' => (int)$row['TotalSelisih']
            ]);
        } else {
            echo json_encode(['error' => 'No items found for this member']);
        }
    } else {
        echo json_encode(['error' => 'Failed to execute query']);
    }

    $query->close();
} else {
    echo json_encode(['error' => 'Method not allowed']);
}

mysqli_close($conn);

?>
