<?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];


ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


if ($method === 'GET') {
    $cKode = $_GET['cKode'] ?? '';
    $cKodeMember = $_GET['cKodeMember'] ?? '';
    $cNamaMember = $_GET['cNamaMember'] ?? '';
    $cKet = $_GET['cKet'] ?? '';
    $nQty = isset($_GET['nQty']) && is_numeric($_GET['nQty']) ? (int)$_GET['nQty'] : 1;

    $queryBarang = $conn->prepare("SELECT * FROM tbbarang WHERE cKode = ?");
    $queryBarang->bind_param("s", $cKode);

    if ($queryBarang->execute()) {
        $result = $queryBarang->get_result();

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

            $cNamaBrg = $barang['cNama'];
            $nHarga = $barang['nHrgJualPerPcs'];

            $nisi = $barang['nIsi'];
            $nisi2 = $barang['nIsi2'];
            $csat3 = $barang['cSat3'];
            
            
            $queryDiscount = $conn->prepare("SELECT nDisc1, nDisc2, nDisc3 
                                            FROM tbdiskonlist 
                                            WHERE ckode = (SELECT ckddl FROM tbmember WHERE ckodecust = ?)");
            $queryDiscount->bind_param("s", $cKodeMember);

            if ($queryDiscount->execute()) {
                $resultDiscount = $queryDiscount->get_result();

                if ($resultDiscount->num_rows > 0) {
                    $discount = $resultDiscount->fetch_assoc();
                    $nDisc1 = $discount['nDisc1'] ?? 0;
                    
                    $totalIsi = $nisi;

                    if ($nQty >= $totalIsi) {
                        $nDisc3 = $discount['nDisc3'] ?? 0;
                        $nDisc2 = 0;
                    } else {
                        $nDisc3 = 0;
                        $nDisc2 = $discount['nDisc2'] ?? 0;
                        
                    }
                } else {
                    $nDisc1 = 0;
                    $nDisc2 = 0;
                    $nDisc3 = 0;
                }
                $queryDiscount->close();
            } else {
                echo json_encode(['error' => 'Gagal mengambil data diskon']);
                exit;
            }
            
            
           $queryJenismember = $conn->prepare("SELECT * 
                                    FROM tbjenismember t
                                    WHERE ckode = (SELECT cjenismember FROM tbmember t WHERE ckodecust = ?)");
            $queryJenismember->bind_param("s", $cKodeMember);
            
            if ($queryJenismember->execute()) {
                $resultJenismember = $queryJenismember->get_result();
            
                if ($resultJenismember->num_rows > 0) {
                    $jenismember = $resultJenismember->fetch_assoc();
                    $nDisc4 = $jenismember['nDisc4'] ?? 0;  
                } else {
                    $nDisc4 = 0;
                }
                $queryJenismember->close();
            } else {
                echo json_encode(['error' => 'Gagal mengambil data jenis member']);
                exit;
            }

            
            

            $nSTotal = $nHarga * $nQty;

            $diskon1 = $nSTotal * ($nDisc1 / 100); 
            $setelahDiskon1 = $nSTotal - $diskon1;
            
            $diskon2 = $setelahDiskon1 * ($nDisc2 / 100);
            $setelahDiskon2 = $setelahDiskon1 - $diskon2;
            
            $diskon3 = $setelahDiskon2 * ($nDisc3 / 100);
            $setelahDiskon3 = $setelahDiskon2 - $diskon3;
            
            $diskon4 = $setelahDiskon3 * ($nDisc4 / 100); // 10%
            $setelahDiskon4 = $setelahDiskon3 - $diskon4;
            
            $nSTotalAfterDisc = $setelahDiskon4;

            $queryMaxNoID = $conn->prepare("SELECT MAX(CAST(cNoID AS UNSIGNED)) AS newNoID FROM tbkeranjang WHERE cKodeMember = ?");
            $queryMaxNoID->bind_param("s", $cKodeMember);

            if ($queryMaxNoID->execute()) {
                $resultMaxNoID = $queryMaxNoID->get_result();
                $row = $resultMaxNoID->fetch_assoc();
                $newNoID = $row['newNoID'] + 1;
                $newNoID = str_pad($newNoID, 3, '0', STR_PAD_LEFT); 
            } else {
                $newNoID = '001';
            }
                    
                

            $queryCheckExisting = $conn->prepare("SELECT * FROM tbkeranjang WHERE cKodeMember = ? AND cKodeBrg = ?");
            $queryCheckExisting->bind_param("ss", $cKodeMember, $cKode);

            if ($queryCheckExisting->execute()) {
                $resultCheckExisting = $queryCheckExisting->get_result();

                if ($resultCheckExisting->num_rows > 0) {
                    $existingItem = $resultCheckExisting->fetch_assoc();
                    $newQty = $nQty;
                    $newSTotal = $newQty * $nHarga;

                    $queryUpdate = $conn->prepare("UPDATE tbkeranjang SET nQty = ?, nSTotal = ? WHERE cKodeMember = ? AND cKodeBrg = ?");
                    $queryUpdate->bind_param("dsss", $newQty, $newSTotal, $cKodeMember, $cKode);

                    if ($queryUpdate->execute()) {
                        echo json_encode(['success' => 'berhasil ditambahkan ke keranjang']);
                    } else {
                        echo json_encode(['error' => 'Gagal memperbarui keranjang']);
                    }
                    $queryUpdate->close();
                } else {
                    
                }
            } else {
                echo json_encode(['error' => 'Gagal memeriksa apakah item ada di keranjang']);
            }

            $queryCheckExisting->close();
        } else {
            echo json_encode(['error' => 'Produk tidak ditemukan']);
        }
    } else {
        echo json_encode(['error' => 'Gagal mengeksekusi query']);
    }

    $queryBarang->close();
} else {
    echo json_encode(['error' => 'Metode tidak diizinkan']);
}

mysqli_close($conn);

?>
