<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

require_once "../account/include/db.php";

// --- ACTION LOGIC (Reverse & Edit) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && isset($_POST['trans_id'])) {
    $trans_id = (int)$_POST['trans_id'];
    $action = $_POST['action'];

    // 1. REVERSE LOGIC (Undo Transfer)
    if ($action === 'reverse') {
        // Fetch transfer details
        $fetch_q = "SELECT sender_id, recipient_id, amount, status FROM internal_transfers WHERE id = ? LIMIT 1";
        if ($stmt = mysqli_prepare($conn, $fetch_q)) {
            mysqli_stmt_bind_param($stmt, "i", $trans_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $s_id, $r_id, $amt, $stat);
            if (mysqli_stmt_fetch($stmt)) {
                mysqli_stmt_close($stmt);

                if ($stat === 'completed') {
                    // Start reversing: Add to Sender, Deduct from Recipient
                    $upd_sender = "UPDATE users SET balance = balance + ? WHERE id = ?";
                    $upd_recip  = "UPDATE users SET balance = balance - ? WHERE id = ?";
                    $upd_trans  = "UPDATE internal_transfers SET status = 'reversed' WHERE id = ?";

                    $s1 = mysqli_prepare($conn, $upd_sender);
                    mysqli_stmt_bind_param($s1, "di", $amt, $s_id);
                    
                    $s2 = mysqli_prepare($conn, $upd_recip);
                    mysqli_stmt_bind_param($s2, "di", $amt, $r_id);
                    
                    $s3 = mysqli_prepare($conn, $upd_trans);
                    mysqli_stmt_bind_param($s3, "i", $trans_id);

                    if (mysqli_stmt_execute($s1) && mysqli_stmt_execute($s2) && mysqli_stmt_execute($s3)) {
                        $_SESSION['swal_success'] = "Transfer reversed successfully. Funds returned to sender.";
                        $_SESSION['swal_title'] = "Reversed!";
                    }
                }
            } else { mysqli_stmt_close($stmt); }
        }
    }
    
    // 2. EDIT LOGIC
    elseif ($action === 'edit' && isset($_POST['new_amount'])) {
        $new_amt = (float)$_POST['new_amount'];
        $new_note = mysqli_real_escape_string($conn, $_POST['new_note']);
        
        $upd_q = "UPDATE internal_transfers SET amount = ?, note = ? WHERE id = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "dsi", $new_amt, $new_note, $trans_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Transfer details updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: manage_transfers.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- SEARCH & PAGINATION SETUP ---
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search Condition
$where_clause = "WHERE 1";
if ($search !== '') {
    $where_clause = "WHERE (u1.full_name LIKE '%$search%' OR u2.full_name LIKE '%$search%' OR t.note LIKE '%$search%')";
}

// Count for pagination
$count_query = "SELECT COUNT(*) as total FROM internal_transfers t 
                JOIN users u1 ON t.sender_id = u1.id 
                JOIN users u2 ON t.recipient_id = u2.id $where_clause";
$total_res = mysqli_query($conn, $count_query);
$total_row = mysqli_fetch_assoc($total_res);
$total_records = $total_row['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

// Fetch Main Data
$query = "SELECT t.*, u1.full_name as sender_name, u2.full_name as recipient_name 
          FROM internal_transfers t 
          JOIN users u1 ON t.sender_id = u1.id 
          JOIN users u2 ON t.recipient_id = u2.id 
          $where_clause 
          ORDER BY t.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Internal Transfers</h1>
        </div>

        <form method="GET" class="flex gap-2 w-full md:w-auto">
            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                   placeholder="Search names or notes..." 
                   class="bg-slate-900 border border-slate-800 text-slate-200 text-sm rounded-lg px-4 py-2 w-full md:w-64 focus:border-blue-500 outline-none">
            <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded-lg text-sm font-bold">Search</button>
        </form>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[900px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Sender</th>
                        <th class="p-4">Recipient</th>
                        <th class="p-4">Amount</th>
                        <th class="p-4">Status</th>
                        <th class="p-4">Date</th>
                        <th class="p-4 text-right">Action</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4 font-bold text-slate-200"><?php echo htmlspecialchars($row['sender_name'] ?? 'System'); ?></td>
                            <td class="p-4 font-bold text-slate-200"><?php echo htmlspecialchars($row['recipient_name'] ?? 'System'); ?></td>
                            <td class="p-4">
                                <span class="text-blue-400 font-mono font-bold">$<?php echo number_format($row['amount'], 2); ?></span>
                            </td>
                            <td class="p-4">
                                <?php if($row['status'] === 'completed'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Completed</span>
                                <?php elseif($row['status'] === 'reversed'): ?>
                                    <span class="status-pill bg-orange-500/10 text-orange-500 border border-orange-500/20">Reversed</span>
                                <?php else: ?>
                                    <span class="status-pill bg-red-500/10 text-red-500 border border-red-500/20"><?php echo $row['status']; ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-xs text-slate-500"><?php echo date('M d, H:i', strtotime($row['created_at'])); ?></td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <?php if($row['status'] === 'completed'): ?>
                                        <form method="POST" class="inline m-0">
                                            <input type="hidden" name="trans_id" value="<?php echo $row['id']; ?>">
                                            <input type="hidden" name="action" value="reverse">
                                            <button type="button" onclick="confirmAction(this.form, 'reverse')" class="text-orange-500 text-[10px] font-bold uppercase hover:underline">Reverse</button>
                                        </form>
                                    <?php endif; ?>

                                    <button onclick="editModal(<?php echo $row['id']; ?>, '<?php echo $row['amount']; ?>', '<?php echo htmlspecialchars($row['note'] ?? ''); ?>')" 
                                            class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-500 italic">No transfers matching your search.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&search=<?php echo $search; ?>" class="pagination-btn px-3 py-1 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>" class="pagination-btn px-3 py-1 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&search=<?php echo $search; ?>" class="pagination-btn px-3 py-1 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function editModal(id, amount, note) {
    Swal.fire({
        title: 'Edit Transfer',
        background: '#0f172a',
        color: '#f1f5f9',
        html: `
            <form id="editForm" method="POST">
                <input type="hidden" name="trans_id" value="${id}">
                <input type="hidden" name="action" value="edit">
                <div class="text-left mb-3"><label class="text-[10px] uppercase font-bold text-slate-500">Amount ($)</label></div>
                <input type="number" step="0.01" name="new_amount" value="${amount}" class="w-full bg-slate-950 border border-slate-800 p-3 rounded mb-4 text-white">
                <div class="text-left mb-3"><label class="text-[10px] uppercase font-bold text-slate-500">Transfer Note</label></div>
                <textarea name="new_note" class="w-full bg-slate-950 border border-slate-800 p-3 rounded text-white h-24">${note}</textarea>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Changes',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('editForm').submit(); }
    });
}

function confirmAction(form, type) {
    Swal.fire({
        title: 'Reverse Funds?',
        text: "This will deduct the amount from the recipient and return it to the sender's balance.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f59e0b',
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Yes, Reverse!',
        background: '#0f172a',
        color: '#f1f5f9'
    }).then((result) => { if (result.isConfirmed) form.submit(); });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>