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

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

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);
    $info = curl_getinfo($ch);

    if (curl_errno($ch)) {
        log_activity("cURL error: " . curl_error($ch) . " - Info: " . print_r($info, true));
        curl_close($ch);
        return null;
    }

    if ($info['http_code'] != 200) {
        log_activity("API request failed with HTTP code: " . $info['http_code'] . " - Response: " . $response);
        curl_close($ch);
        return null;
    }

    curl_close($ch);
    return $response;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on bayar_iuran.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 bayar_iuran.php");
    exit;
}

try {
    // Validasi token
    $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 bayar_iuran.php");
        exit;
    }

    $user_id = $tokenData['user_id'];
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['iuran_id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required field: iuran_id']);
        log_activity("Missing required field: iuran_id in bayar_iuran.php");
        exit;
    }

    $iuran_id = $input['iuran_id'];
    $currentMonth = date('Y-m-01');

    // Cek apakah user sudah membayar iuran bulan ini
    $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM pembayaran_iuran WHERE user_id = ? AND iuran_id = ? AND DATE_FORMAT(tanggal_bayar, '%Y-%m-01') = ?");
    $stmt->execute([$user_id, $iuran_id, $currentMonth]);
    $paymentCheck = $stmt->fetch();

    if ($paymentCheck['total'] > 0) {
        http_response_code(400);
        echo json_encode(['error' => 'Iuran sudah dibayar bulan ini']);
        log_activity("User ID '$user_id' mencoba membayar iuran yang sudah dibayar bulan ini.");
        exit;
    }

    // Cek informasi iuran
    $stmt = $pdo->prepare("SELECT nama, nominal FROM jenis_iuran WHERE id = ? AND status = 'aktif'");
    $stmt->execute([$iuran_id]);
    $iuran = $stmt->fetch();

    if (!$iuran) {
        http_response_code(404);
        echo json_encode(['error' => 'Iuran not found or inactive']);
        log_activity("Iuran not found or inactive in bayar_iuran.php");
        exit;
    }

    $nominal = $iuran['nominal'];
    $iuran_nama = $iuran['nama']; // Ambil nama iuran

    // Ambil wallet pengguna
    $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'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Wallet not found']);
        log_activity("Wallet not found for user ID '$user_id'");
        exit;
    }

    // Kirim pembayaran menggunakan saldo blockchain
    $response = curl_request('https://blockchain.sisiteknis.com/sendToken', 'POST', [
        'privateKey' => openssl_decrypt($userData['private_key'], 'AES-256-CBC', 'YOUR_VERY_STRONG_KEY', 0, 'a_random_iv'),
        'to' => 'ebc_a6ac73196b9fff9c9afe042f5c2adba5a637303d', // Wallet tujuan pembayaran iuran
        'amount' => $nominal,
        'contractAddress' => 'ebc_1e0b995b44819d162a523762ae313571fba442ab670e62cb7504567c3539a364',
    ]);

    $responseData = json_decode($response, true);
    if (!$responseData || !isset($responseData['txHash'])) {
        http_response_code(500);
        echo json_encode(['error' => 'Transaction failed']);
        log_activity("Transaction failed for user ID '$user_id'");
        exit;
    }

    $transactionHash = $responseData['txHash'];

    // Mulai transaksi database
    $pdo->beginTransaction();

    // Simpan pembayaran ke database
    $stmt = $pdo->prepare("INSERT INTO pembayaran_iuran (user_id, iuran_id, jumlah_bayar, metode_pembayaran, tx_hash, status, tanggal_bayar) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $success = $stmt->execute([$user_id, $iuran_id, $nominal, 'blockchain', $transactionHash, 'success']);

    if (!$success) {
        throw new Exception("Failed to insert pembayaran_iuran");
    }

    // Simpan transaksi ke tabel transactions
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, to_address, type, amount, contract_address, keterangan, transaction_hash, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $success = $stmt->execute([$user_id,'ebc_a6ac73196b9fff9c9afe042f5c2adba5a637303d', 'saldo', $nominal,'ebc_1e0b995b44819d162a523762ae313571fba442ab670e62cb7504567c3539a364', "Pembayaran iuran: $iuran_nama", $transactionHash, 'success']);

    if (!$success) {
        throw new Exception("Failed to insert transactions");
    }

    // Commit transaksi database
    $pdo->commit();

    http_response_code(200);
    echo json_encode(['message' => 'Iuran paid successfully', 'txHash' => $transactionHash]);
    log_activity("Iuran paid successfully for user ID '$user_id'. Transaction hash: $transactionHash");

} catch (PDOException $e) {
    $pdo->rollBack();
    http_response_code(500);
    log_activity("Database error in bayar_iuran.php: " . $e->getMessage());
    echo json_encode(['error' => 'Database error', 'details' => $e->getMessage()]);
} catch (Exception $e) {
    $pdo->rollBack();
    http_response_code(500);
    log_activity("bayar_iuran.php error: " . $e->getMessage());
    echo json_encode(['error' => $e->getMessage()]);
}

?>
