<?php

require_once "config.php";

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

$method = $_SERVER['REQUEST_METHOD'];

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

        if (!empty($kode)) {
            $kurirQuery = $conn->prepare("
                SELECT 
                    CAST(SUM(nstotal) AS UNSIGNED) as cost,
                    cjnskurir  as etd
                FROM tbkeranjang 
                WHERE cKodeMember = ? 
                LIMIT 1
            ");
            $kurirQuery->bind_param("s", $kode);
            $kurirQuery->execute();
            $kurirResult = $kurirQuery->get_result();
            $kurirData = $kurirResult->fetch_all(MYSQLI_ASSOC);

            if (!empty($kurirData)) {
                $kurirData[0]['cost'] = "Rp " . number_format($kurirData[0]['cost'], 0, ',', '.');
            }

            echo json_encode($kurirData);
        } else {
            echo json_encode(["error" => "No 'kode' parameter provided"]);
        }
        break;

    case 'PUT':
        $putData = json_decode(file_get_contents("php://input"), true);
        $kode = isset($putData['kode']) ? $putData['kode'] : '';
        $newKurir = isset($putData['cjnskurir']) ? $putData['cjnskurir'] : '';
        $newCnamakurir = isset($putData['cnamakurir']) ? $putData['cnamakurir'] : '';
        $newCkodekurir = isset($putData['ckodekurir']) ? $putData['ckodekurir'] : '';
        $newCservicekurir = isset($putData['cservicekurir']) ? $putData['cservicekurir'] : '';
        $newCdescriptionkurir = isset($putData['cdescriptionkurir']) ? $putData['cdescriptionkurir'] : '';
        $newCcostkurir = isset($putData['ccostkurir']) ? $putData['ccostkurir'] : '';
        $newCetdkurir = isset($putData['cetdkurir']) ? $putData['cetdkurir'] : '';
    
        if (!empty($kode)) {
            $updateQuery = $conn->prepare("
                UPDATE tbkeranjang 
                SET 
                    cjnskurir = ?, 
                    cnamakurir = ?, 
                    ckodekurir = ?, 
                    cservicekurir = ?, 
                    cdescriptionkurir = ?, 
                    ccostkurir = ?, 
                    cetdkurir = ? 
                WHERE cKodeMember = ?
            ");
            $updateQuery->bind_param("ssssssss", $newKurir, $newCnamakurir, $newCkodekurir, $newCservicekurir, $newCdescriptionkurir, $newCcostkurir, $newCetdkurir, $kode);
            
            if ($updateQuery->execute()) {
                echo json_encode(["success" => "Data updated successfully"]);
            } else {
                echo json_encode(["error" => "Failed to update data"]);
            }
        } else {
            echo json_encode(["error" => "Invalid 'kode' or 'cjnskurir' parameter"]);
        }
        break;
}

mysqli_close($conn);

?>
