<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include "../apifunctions.php";
include "../../config/connectdb.php";
include "../../config/utilities.php";

$body = file_get_contents("php://input");
$reqBody = json_decode($body, true);

if (!$reqBody || !isset($reqBody['event'])) {
    http_response_code(400);
    echo json_encode(["status" => false, "message" => "Invalid webhook payload."]);
    exit;
}

if ($reqBody['event'] === 'collection.virtualaccount.successful') {
    $eventType = "CREDIT ACCOUNT";

    // Log webhook data first
    $stmtLog = $connect->prepare("INSERT INTO webhooks (type, data) VALUES (?, ?)");
    $stmtLog->bind_param("ss", $eventType, $body);
    $stmtLog->execute();
    $stmtLog->close();

    $reqData = $reqBody['data'];

    $transaction_reference = uniqid('ESTATE_', true) . time();
    $channel = 'RESERVED_ACCOUNT';
    $amount = $reqData['amount'];
    $settled_amount = $reqData['netAmount'];
    $charge = $reqData['charge'];
    $source_account_number = $reqData['sender']['originatorAccountNumber'];
    $source_account_name = $reqData['sender']['originatorName'];
    $source_account_bank = $reqData['sender']['originatorBank'];
    $narration = $reqData['meta']['notification']['narration'];
    $created_at = time();
    $reserved_account_number = $reqData['recipient'];

    $connect->begin_transaction();

    try {
        $stmtFind = $connect->prepare("SELECT user_id, internal_reference FROM reserved_accounts WHERE account_number = ?");
        $stmtFind->bind_param("s", $reserved_account_number);
        $stmtFind->execute();
        $stmtFind->store_result();
        
        if ($stmtFind->num_rows === 0) {
            throw new Exception("Account not found for reserved account number: $reserved_account_number");
        }
        
        $stmtFind->bind_result($user_id, $reserved_internal_ref);
        $stmtFind->fetch();
        $stmtFind->close();
        
        // Step: Fetch household_id and wallet_id for the user
        $userMeta = fetch_any_data($connect, 'user_access', ['household_id'], ['id' => $user_id]);
        $household_id = $userMeta['household_id'];
        $wallet_id = fetch_any_data($connect, 'account_wallets', ['id'], ['household_id' => $household_id])['id']; // Adjust if wallet IDs are used per user
        $internal_reference = 'ADMIN_' . substr(md5(uniqid()), 0, 14) . $created_at;
        $gateway_reference = 'GATEWAY_' . substr(md5(uniqid()), 0, 14);
        $source_account = 'main_wallet'; // Or from webhook if dynamic
        
        // Step: Get latest balance_before
        $balanceBefore = getBalance($connect, $household_id);
        
        // Insert into account_credits_temporary
        $stmtTempFull = $connect->prepare("INSERT INTO account_credits_temporary (household_id, wallet_id, amount, charge, internal_reference, gateway_reference, source_account, time ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmtTempFull->bind_param("iiissssi", $household_id, $wallet_id, $amount, $charge, $internal_reference, $gateway_reference, $source_account, $created_at);
        $stmtTempFull->execute();
        $stmtTempFull->close();
        
        // Step: Fetch user_identity
        $user_identity = fetch_any_data($connect, 'user_access', ['user_identity'], ['id' => $user_id])['user_identity'];
      
        // Calculate balance after
        $balanceAfter = getBalance($connect, $household_id);
        $timestamp = time();
        $transaction_type = "CREDIT";
        $transaction_narration = "Account funded by ".$source_account_name;
        // Insert into account_statement
        $stmtStatement = $connect->prepare("INSERT INTO account_statement (household_id, amount, charges, balance_before, balance_after, wallet_id, internal_reference, transaction_type, transaction_narration, user_identity, timestamp ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmtStatement->bind_param("issiisssssi", $household_id, $amount, $charge, $balanceBefore, $balanceAfter, $wallet_id, $internal_reference, $transaction_type, $transaction_narration, $user_identity, $timestamp);
        $stmtStatement->execute();
        
        
        if (!$stmtStatement->execute()) {
            error_log("Insert failed: " . $stmtStatement->error);
            echo $stmtStatement->error;
        }
        
        $stmtStatement->close();

        // // Log reserved_account_webhook
        // $stmtWebhook = $connect->prepare("INSERT INTO reserved_account_webhook (data, txnref, userId, `timestamp`) VALUES (?, ?, ?, ?)");
        // $stmtWebhook->bind_param("ssss", $body, $transaction_reference, $user_id, $created_at);
        // $stmtWebhook->execute();
        // $stmtWebhook->close();

        // // Insert into credit_records_temporary
        // $stmtTemp = $connect->prepare("INSERT INTO credit_records_temporary (account_id, reference, transaction_amount, amount_settled, currency, channel) VALUES (?, ?, ?, ?, 'NGN', ?)");
        // $stmtTemp->bind_param("sssss", $user_id, $transaction_reference, $amount, $settled_amount, $channel);
        // $stmtTemp->execute();
        // $stmtTemp->close();

        // // Insert into credit_records
        // $stmtPerm = $connect->prepare("INSERT INTO credit_records (account_id, reference, transaction_amount, amount_settled, currency, channel, status) VALUES (?, ?, ?, ?, 'NGN', ?, 'Successful')");
        // $stmtPerm->bind_param("sssss", $user_id, $transaction_reference, $amount, $settled_amount, $channel);
        // $stmtPerm->execute();
        // $stmtPerm->close();

        $connect->commit();

        http_response_code(200);
        echo json_encode(["status" => "success", "message" => "Transaction processed successfully."]);
        exit;

    } catch (Exception $e) {
        $connect->rollback();

        $err = $connect->real_escape_string($e->getMessage());
        mysqli_query($connect, "INSERT INTO failed_sql_query (type, error_message) VALUES ('Reserved Account Credit', '$err')");

        http_response_code(500);
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
        exit;
    }
}

// Unknown event fallback
http_response_code(200);
echo json_encode(["status" => true, "message" => "Event received but not handled."]);
