<?php

require_once "config.php";
header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $ckodecust = $_GET['ckodecust'] ?? '';

        if ($ckodecust === '') {
            echo json_encode([
                [
                    "ckode"      => "",
                    "cnama"      => "",
                    "npoin"      => "",
                    "cfileimage" => "",
                    "totalpoin"  => 0,
                    "status"     => ""
                ]
            ]);
            exit;
        }

        $stmt = $conn->prepare("
            SELECT 
                r.ckode,
                r.cnama,
                r.npoin,
                r.cfileimage,
                IFNULL(p.totalpoin, 0) AS totalpoin,
                CASE 
                    WHEN IFNULL(p.totalpoin, 0) >= r.npoin THEN 'BISA DITUKAR'
                    ELSE 'BELUM CUKUP POIN'
                END AS status
            FROM tbreward r
            CROSS JOIN (
                SELECT IFNULL(FLOOR(SUM(npoin)), 0) AS totalpoin 
                FROM tbbukupoin 
                WHERE ckodecust = ?
            ) p
        ");

        $stmt->bind_param("s", $ckodecust);
        $stmt->execute();
        $result = $stmt->get_result();

        $rows = [];
        while ($row = $result->fetch_assoc()) {
            $row['totalpoin'] = (int)$row['totalpoin'];
            $rows[] = $row;
        }

        echo json_encode($rows);
        break;
}

$conn->close();
