<?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $cKodeMember = $_GET['cKodeMember'] ?? '';
    $cKodeBrg = $_GET['ckode'] ?? '';
    $nQty = $_GET['nQty'] ?? 1;

    $queryBarang = $conn->prepare("SELECT cNama, nHrgJualPerPcs, nIsi, nIsi2 FROM tbbarang WHERE cKode = ?");
    $queryBarang->bind_param("s", $cKodeBrg);
    $queryBarang->execute();
    $resultBarang = $queryBarang->get_result();
    $barang = $resultBarang->fetch_assoc();
    $queryBarang->close();

    if (!$barang) {
        echo json_encode(['error' => 'Product not found']);
        exit;
    }

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

    $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();

    if (!$discount) {
        echo json_encode(['error' => 'Discount data not found']);
        exit;
    }

    $nDisc1 = (int) ($discount['nDisc1'] ?? 0);
    $totalIsi = $nisi;
    // $totalIsi = $nisi * $nisi2;

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

    $nSTotal = $nHarga * $newQty;
    $afterDisc1 = $nSTotal - ($nSTotal * $nDisc1 / 100);
    $afterDisc2 = $afterDisc1 - ($afterDisc1 * $nDisc2 / 100);
    $afterDisc3 = $afterDisc2 - ($afterDisc2 * $nDisc3 / 100);
    $nSTotalAfterDisc = (int) $afterDisc3;

    $selisih = ($nHarga * $newQty) - $nSTotalAfterDisc;

    $nDiscTotal = ($nHarga * $newQty) - $nSTotalAfterDisc;

    $nDiscPercentage = ($nDiscTotal / ($nHarga * $newQty)) * 100;

    $selisihFormatted = 'Rp. ' . number_format($selisih, 0, ',', '.');
    $nSTotalAfterDiscFormatted = 'Rp. ' . number_format($nSTotalAfterDisc, 0, ',', '.');
    $nDiscTotalFormatted = 'Rp. ' . number_format($nDiscTotal, 0, ',', '.');

    $response = [
        'cKodeBrg' => $cKodeBrg,
        'cNama' => $barang['cNama'],
        'nQty' => $newQty,
        'nHarga' => $nHarga,
        'nDisc1' => $nDisc1,
        'nDisc2' => $nDisc2,
        'nDisc3' => $nDisc3,
        'nSTotalAfterDisc' => $nSTotalAfterDiscFormatted,
        'selisih' => $selisihFormatted,
        'nDiscTotal' => $nDiscTotalFormatted,
        'nDiscPercentage' => number_format($nDiscPercentage, 2)
    ];

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

mysqli_close($conn);

?>
