<?php
include 'includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the raw POST data
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
        exit;
    }

    // Sanitize and retrieve form inputs
    $bankId = isset($data['bank_id']) ? (int) $data['bank_id'] : 0;
    $amount = isset($data['amount']) ? (float) $data['amount'] : 0;
    $note = isset($data['note']) ? htmlspecialchars($data['note']) : '';
    $date = isset($data['date']) ? $data['date'] : date('Y-m-d');

    if ($bankId <= 0 || $amount <= 0 || empty($date)) {
        echo json_encode(['status' => 'error', 'message' => 'Please fill out all fields properly.']);
        exit;
    }

    try {
        // Prepare the insert statement
        $stmt = $conn->prepare("
            INSERT INTO bank_debit_amount (bank_id, amount, note, date)
            VALUES (:bank_id, :amount, :note, :date)
        ");
        $stmt->execute([
            'bank_id' => $bankId,
            'amount' => $amount,
            'note' => $note,
            'date' => $date
        ]);

        // Get the last inserted ID (this will be the withdrawal_id)
        $withdrawalId = $conn->lastInsertId();

        // Return success response with withdrawal_id
        echo json_encode([
            'status' => 'success',
            'message' => 'Withdrawal successfully recorded.',
            'withdrawal_id' => $withdrawalId
        ]);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Error occurred while processing the withdrawal.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
