<?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') {
    $cNoID = $_GET['cNoID'] ?? '';
    $nQty = (int) $_GET['nQty'];
    $cKodeMember = $_GET['cKodeMember'] ?? '';

    // Step 1: Ambil nQty dan cKodeBrg dari tbkeranjang
    $query = $conn->prepare("SELECT nQty, cKodeBrg FROM tbkeranjang WHERE cNoID = ? AND cKodeMember = ?");
    $query->bind_param("ss", $cNoID, $cKodeMember);

    if ($query->execute()) {
        $result = $query->get_result();
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $cKodeBrg = $row['cKodeBrg'];
            
            
            // Step 2: Ambil data barang berdasarkan cKodeBrg
                $queryBarang = $conn->prepare("SELECT cNama, nHrgJualPerPcs, nIsi, nIsi2, nMinEcer FROM tbbarang WHERE cKode = ?");
                $queryBarang->bind_param("s", $cKodeBrg);
                $queryBarang->execute();
                $resultBarang = $queryBarang->get_result();
                $barang = $resultBarang->fetch_assoc();
                $queryBarang->close();

                $nHarga = $barang['nHrgJualPerPcs'];
                $nisi =  (int)$barang['nIsi'];
                $nisi2 =  (int) $barang['nIsi2'];
                $nMinEcer =  (int) $barang['nMinEcer'];

                // Step 3: Ambil diskon berdasarkan cKodeMember
                $queryDiscount = $conn->prepare("SELECT nDisc1, nDisc2, nDisc3 
                                                 FROM tbdiskonlist 
                                                 WHERE ckode = (SELECT ckddl FROM tbmember WHERE ckodecust = ?)");
                $queryDiscount->bind_param("s", $cKodeMember);
                $queryDiscount->execute();
                $resultDiscount = $queryDiscount->get_result();
                $discount = $resultDiscount->fetch_assoc();
                $queryDiscount->close();

                $nDisc1 = $discount['nDisc1'] ?? 0;
                $totalIsi = $nisi;
                // $totalIsi = $nisi * $nisi2;
                
                if ($nQty == 1 || $nQty == 0) { 
                    if ($nQty == 0) {
                        $newQty = $nMinEcer;
                    } else {
                        $newQty = $nQty;
                    }
                } else {
                    if ($nQty < $nMinEcer) {
                        $newQty = $nMinEcer;
                    } else {
                        $newQty = $nQty;
                    }
                }

                if ($nMinEcer <= 0) $nMinEcer = 1;
                $newQty = $nQty - 1;
                if ($newQty < $nMinEcer) $newQty = $nMinEcer;
                
                if ($newQty >= $totalIsi) {
                    $nDisc3 = (int)  $discount['nDisc3'] ?? 0;
                    $nDisc2 = 0;
                } else {
                    $nDisc3 = 0;
                    $nDisc2 = (int) $discount['nDisc2'] ?? 0;
                                
                }

                $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;
                }
    
    

                // Step 5: Hitung ulang diskon bertingkat
                $nSTotal = $nHarga * $newQty;
                $afterDisc1 = $nSTotal - ($nSTotal * $nDisc1 / 100);
                $afterDisc2 = $afterDisc1 - ($afterDisc1 * $nDisc2 / 100);
                $afterDisc3 = $afterDisc2 - ($afterDisc2 * $nDisc3 / 100);
                $afterDisc4 = $afterDisc3 - ($afterDisc3 * $nDisc4 / 100);
                $nSTotalAfterDisc = $afterDisc4;


                    // var_dump($nQty); 
                    // var_dump($nHarga); 
                    // var_dump($newQty);  
                    // var_dump($nSTotal); 
                    // var_dump($afterDisc1); 
                    // var_dump($afterDisc2); 
                    // var_dump($afterDisc3); 
                    // var_dump($afterDisc4); 
                $updateQuery = $conn->prepare("UPDATE tbkeranjang 
                                               SET nQty = ?, 
                                                   nSTotal = ?, 
                                                   nDisc2 = ?,
                                                   nDisc3 = ?,
                                                   nDisc4 = ?
                                               WHERE cNoID = ? AND cKodeMember = ?");
                            $updateQuery->bind_param("ddsssss", $newQty, $nSTotalAfterDisc, $nDisc2,  $nDisc3, $nDisc4, $cNoID,  $cKodeMember);

                if ($updateQuery->execute()) {
                    echo json_encode([
                    'nQty'  => (int)$newQty
                    ]);
                } else {
                    echo json_encode(['error' => 'Failed to update quantity and total']);
                }
                $updateQuery->close();
        } else {
            echo json_encode(['error' => 'Item not found']);
        }
    } else {
        echo json_encode(['error' => 'Failed to execute query']);
    }

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

mysqli_close($conn);

?>
