<?php
// bayarsemua.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on bayarsemua.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in bayarsemua.php");
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in bayarsemua.php");
        exit;
    }

    $user_id = $tokenData['user_id'];

    $stmt = $pdo->prepare("SELECT k.id, p.id AS produk_id, p.judul, p.harga, p.diskon, p.kuantitas, k.jumlah, p.id_penjual, u.wallet_address
        FROM keranjang k
        JOIN produk p ON k.produk_id = p.id
        JOIN users u ON p.id_penjual = u.id
        WHERE k.user_id = ?");
    $stmt->execute([$user_id]);
    $keranjang = $stmt->fetchAll();

    if (empty($keranjang)) {
        http_response_code(400);
        echo json_encode(['error' => 'Keranjang is empty']);
        exit;
    }

    $transactions = [];

    foreach ($keranjang as $item) {
        if ($item['kuantitas'] < $item['jumlah']) {
            log_activity("Stock not sufficient for product '{$item['judul']}'");
            continue;
        }

        $harga_diskon = $item['harga'] - ($item['harga'] * $item['diskon'] / 100);
        $total_harga = $harga_diskon * $item['jumlah'];
        $penjual_wallet = $item['wallet_address'];
        $product_title = $item['judul'];

        $stmt = $pdo->prepare("SELECT wallet_address, private_key FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $userData = $stmt->fetch();

        if (!$userData || empty($userData['wallet_address']) || empty($userData['private_key'])) {
            log_activity("Wallet not found for user ID '$user_id'");
            continue;
        }

        $decryptedPrivateKey = openssl_decrypt($userData['private_key'], 'AES-256-CBC', 'YOUR_VERY_STRONG_KEY', 0, 'a_random_iv');

        if (!$decryptedPrivateKey) {
            log_activity("Failed to decrypt private key for user ID '$user_id'");
            continue;
        }

        $contractAddress = 'ebc_1e0b995b44819d162a523762ae313571fba442ab670e62cb7504567c3539a364';
        $response = curl_request('https://blockchain.sisiteknis.com/sendToken', 'POST', [
            'privateKey' => $decryptedPrivateKey,
            'to' => $penjual_wallet,
            'amount' => $total_harga,
            'contractAddress' => $contractAddress,
        ]);

        log_activity("sendToken response: " . $response);

        $responseData = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE || !isset($responseData['txHash'])) {
            log_activity("Transaction failed for product '$product_title'");
            continue;
        }

        $transactionHash = $responseData['txHash'];
        $status = isset($responseData['status']) && $responseData['status'] === 'success' ? 'success' : 'failed';

        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, to_address, amount, type, contract_address, transaction_hash, status, keterangan) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $user_id,
            $penjual_wallet,
            $total_harga,
            'saldo',
            $contractAddress,
            $transactionHash,
            $status,
            "Pembayaran untuk produk '$product_title'"
        ]);

        if ($status === 'success') {
            // Mengurangi kuantitas stok produk dan menambah jumlah pembelian
            $stmt = $pdo->prepare("UPDATE produk SET kuantitas = kuantitas - ?, pembelian = pembelian + ? WHERE id = ?");
            $stmt->execute([$item['jumlah'], $item['jumlah'], $item['produk_id']]);
            
            // Menghapus produk dari keranjang setelah pembayaran berhasil
            $stmt = $pdo->prepare("DELETE FROM keranjang WHERE id = ?");
            $stmt->execute([$item['id']]);
        }

        $transactions[] = [
            'product' => $product_title,
            'transaction_hash' => $transactionHash,
            'status' => $status
        ];
    }

    http_response_code(200);
    echo json_encode(['message' => 'Payments processed', 'transactions' => $transactions]);
    log_activity("Payments processed for user ID '$user_id'");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("bayarsemua.php error: " . $e->getMessage());
    exit;
}

function curl_request($url, $method, $data = null) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}?>
