<?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']) : '';
$bank_name = isset($_POST['bank_name']) ? trim($_POST['bank_name']) : '';
$account_name = isset($_POST['account_name']) ? trim($_POST['account_name']) : '';
$account_number = isset($_POST['account_number']) ? trim($_POST['account_number']) : '';

// Validate inputs
$errors = [];

if (empty($bank_name)) {
    $errors['bank_name'] = 'Bank name is required';
}

if (empty($account_name)) {
    $errors['account_name'] = 'Account name is required';
} elseif (!preg_match('/^[a-zA-Z ]{3,}$/', $account_name)) {
    $errors['account_name'] = 'Account name must be at least 3 letters with no numbers';
}

if (empty($account_number)) {
    $errors['account_number'] = 'Account number is required';
} elseif (!preg_match('/^\d{10}$/', $account_number)) {
    $errors['account_number'] = 'Account number must be exactly 10 digits';
}

if (!empty($errors)) {
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit();
}

try {
    // First verify the account belongs to this 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();
    }

    // Update account
    $stmt = $conn->prepare("UPDATE vendor_bank_accounts 
                          SET bank_name = ?, account_name = ?, account_number = ?, updated_at = NOW()
                          WHERE id = ? AND vendor_id = ?");
    $stmt->bind_param("sssss", $bank_name, $account_name, $account_number, $account_id, $vendor_id);
    
    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            echo json_encode(['success' => true, 'message' => 'Bank account updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'No changes were made']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update account']);
    }
} catch (Exception $e) {
    error_log("Database error in update_bank_account.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>