<?php
session_start();
include('../../includes/config.php');

header('Content-Type: application/json');

// Only accountants or admin
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 4])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Accept single or multiple link IDs
$link_ids = $_POST['link_ids'] ?? [];
if (is_string($link_ids)) {
    $link_ids = [intval($link_ids)];
} elseif (is_array($link_ids)) {
    $link_ids = array_map('intval', $link_ids);
}

if (empty($link_ids)) {
    echo json_encode(['success' => false, 'message' => 'No reconciliation link(s) provided.']);
    exit;
}

$success_ids = [];
$failed_ids = [];

$conn->begin_transaction();

try {
    foreach ($link_ids as $link_id) {
        // Get reconciliation link details
        $stmt = $conn->prepare("
            SELECT bank_transaction_id, financial_transaction_id, reconciled_amount 
            FROM deposit_reconciliation_links 
            WHERE id = ?
        ");
        $stmt->bind_param("i", $link_id);
        $stmt->execute();
        $stmt->bind_result($bt_id, $ft_id, $amount);
        if (!$stmt->fetch()) {
            $stmt->close();
            $failed_ids[] = $link_id;
            continue;
        }
        $stmt->close();

        // Delete link
        $del = $conn->prepare("DELETE FROM deposit_reconciliation_links WHERE id = ?");
        $del->bind_param("i", $link_id);
        $del->execute();
        $del->close();

        // Reset FT
        $reset_ft = $conn->prepare("
            UPDATE financial_transactions 
            SET reconciliation_status = 'pending', linked_bank_transaction_id = NULL, credit = 0.00, updated_at = NOW()
            WHERE id = ?
        ");
        $reset_ft->bind_param("i", $ft_id);
        $reset_ft->execute();
        $reset_ft->close();

        // Check if bank_transaction still has other links
        $check = $conn->prepare("SELECT COUNT(*) FROM deposit_reconciliation_links WHERE bank_transaction_id = ?");
        $check->bind_param("i", $bt_id);
        $check->execute();
        $check->bind_result($count);
        $check->fetch();
        $check->close();

        if ($count == 0) {
            $reset_bt = $conn->prepare("
                UPDATE bank_transactions 
                SET reconciliation_status = 'pending', updated_at = NOW() 
                WHERE id = ?
            ");
            $reset_bt->bind_param("i", $bt_id);
            $reset_bt->execute();
            $reset_bt->close();
        }

        // Log
        $log = $conn->prepare("
            INSERT INTO reconciliation_audit_logs
            (event_type, bank_transaction_id, financial_transaction_id, user_id, amount)
            VALUES ('rolled_back', ?, ?, ?, ?)
        ");
        $log->bind_param("iiid", $bt_id, $ft_id, $_SESSION['user_id'], $amount);
        $log->execute();
        $log->close();

        $success_ids[] = $link_id;
    }

    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Rollback complete.',
        'rolled_back' => $success_ids,
        'failed' => $failed_ids
    ]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Rollback failed: ' . $e->getMessage()
    ]);
}
