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

// Validate inputs
$errors = [];

if (empty($bank_name)) {
    $errors['bank'] = 'Please select a bank';
}

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

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

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

try {
    // Check if vendor already has an account
    $check = $conn->prepare("SELECT id FROM vendor_bank_accounts WHERE vendor_id = ?");
    $check->bind_param("s", $vendor_id);
    $check->execute();
    
    if ($check->get_result()->num_rows > 0) {
        echo json_encode(['success' => false, 'message' => 'You can only have one bank account']);
        exit();
    }

    // Insert new account
    $stmt = $conn->prepare("INSERT INTO vendor_bank_accounts 
                          (vendor_id, bank_name, account_name, account_number) 
                          VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $vendor_id, $bank_name, $account_name, $account_number);
    
    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Bank account added successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add account']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>