<?php

require_once "config.php";

date_default_timezone_set('Asia/Jakarta');
$conn->query("SET time_zone = '+07:00'");

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

if (isset($_GET['debug'])) {
    $result = $conn->query("SELECT NOW() as mysql_time");
    $row = $result->fetch_assoc();
    echo json_encode([
        "php_time" => date('Y-m-d H:i:s'),
        "mysql_time" => $row['mysql_time']
    ]);
    exit;
}

function formatRupiah($angka)
{
    return 'Rp' . number_format($angka, 2, ',', '.');
}

switch ($method) {
    case 'GET':
        try {
            $query = $conn->prepare("
                SELECT d.*, t.*
                FROM tbbarang t
                INNER JOIN tbbarangdiskon d ON t.cKode = d.cKode
            ");
            $query->execute();
            $result = $query->get_result();
            $data = $result->fetch_all(MYSQLI_ASSOC);

            foreach ($data as &$item) {
                if (isset($item['nHrgJualPerPcs']) && isset($item['Diskon'])) {
                    $hrgJual = floatval($item['nHrgJualPerPcs']);
                    $diskon = floatval($item['Diskon']);
                    $hrgSetelahDiskon = $hrgJual - ($hrgJual * $diskon / 100);
                    $item['lBuy1get1'] = formatRupiah($hrgSetelahDiskon);
                }
                
                if (isset($item['nHrgBeliNet'])) {
                    $item['nHrgBeliNet'] = formatRupiah($item['nHrgBeliNet']);
                }
                if (isset($item['nHrgBeliPerPcs'])) {
                    $item['nHrgBeliPerPcs'] = formatRupiah($item['nHrgBeliPerPcs']);
                }
                if (isset($item['nHrgJualPerPcs'])) {
                    $item['nHrgJualPerPcs'] = formatRupiah($item['nHrgJualPerPcs']);
                }
            }



            if (!empty($data)) {
                echo json_encode($data);
            } else {
                echo json_encode([
                    "message" => "Tidak ada diskon aktif saat ini.",
                    "status" => "empty"
                ]);
            }

        } catch (Exception $e) {
            echo json_encode([
                "error" => "Terjadi kesalahan saat mengambil data.",
                "message" => $e->getMessage()
            ]);
        }
        break;

    default:
        echo json_encode([
            'error' => 'Invalid request method.',
            'allowed_method' => 'GET'
        ]);
        break;
}

mysqli_close($conn);
?>
