<?php
// update_user_bank_info.php

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

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

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

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

// Mendapatkan input JSON dari body
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);

// Validasi JSON
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON']);
    log_activity("Invalid JSON input in update_user_bank_info.php");
    exit;
}

$namabank = isset($input['namabank']) ? trim($input['namabank']) : null;
$cabang   = isset($input['cabang']) ? trim($input['cabang']) : null;
$norek    = isset($input['norek']) ? trim($input['norek']) : null;

// Validasi parameter input
if (empty($namabank) || empty($cabang) || empty($norek)) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields: namabank, cabang, norek']);
    log_activity("Missing required fields in update_user_bank_info.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan 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 update_user_bank_info.php");
        exit;
    }

    $userId = $tokenData['user_id'];

    // 2) Update data bank user pada tabel users
    $stmt = $pdo->prepare("UPDATE users SET namabank = ?, cabang = ?, norek = ? WHERE id = ?");
    $stmt->execute([$namabank, $cabang, $norek, $userId]);

    // Periksa apakah baris telah diupdate
    if ($stmt->rowCount() > 0) {
        http_response_code(200);
        echo json_encode(['success' => 'Bank information updated successfully']);
        log_activity("Bank information updated for user ID '$userId'.");
    } else {
        // Jika tidak ada perubahan (misalnya data sama dengan sebelumnya)
        http_response_code(200);
        echo json_encode(['info' => 'No changes made or bank information already up-to-date']);
        log_activity("No update needed for user ID '$userId' in update_user_bank_info.php.");
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("update_user_bank_info.php error: " . $e->getMessage());
    exit;
}
?>
