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

session_start();
if (!isset($_SESSION['vendor_id']) || empty($_SESSION['vendor_id'])) {
    echo json_encode(['success' => false, 'message' => 'Session expired']);
    exit();
}

$vendor_id = $_SESSION['vendor_id'];
$account_id = isset($_POST['account_id']) ? trim($_POST['account_id']) : '';

if (empty($account_id)) {
    echo json_encode(['success' => false, 'message' => 'Account ID is required']);
    exit();
}

try {
    // First check if the account exists and belongs to the vendor
    $checkStmt = $conn->prepare("SELECT id FROM vendor_bank_accounts WHERE id = ? AND vendor_id = ?");
    $checkStmt->bind_param("ss", $account_id, $vendor_id);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();
    
    if ($checkResult->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Bank account not found or not authorized']);
        exit();
    }

    // Delete account
    $stmt = $conn->prepare("DELETE FROM vendor_bank_accounts WHERE id = ? AND vendor_id = ?");
    $stmt->bind_param("ss", $account_id, $vendor_id);
    
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            echo json_encode(['success' => true, 'message' => 'Bank account deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'No account was deleted']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete account']);
    }
} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>