<?php
session_start();

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

require 'db/db.php';

if (!isset($_GET['uid']) || !is_numeric($_GET['uid'])) {
    die("No valid user selected");
}

$uid = (int)$_GET['uid'];

// Fetch user
$userQ = mysqli_query($conn, "SELECT full_name, account_number, account_balance FROM users WHERE id = $uid LIMIT 1");
if (mysqli_num_rows($userQ) !== 1) {
    die("User not found");
}
$user = mysqli_fetch_assoc($userQ);

// ────────────────────────────────────────────────
// HANDLE DELETE (same page)
if (isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['tid'])) {
    $tid = (int)$_POST['tid'];

    $txQ = mysqli_query($conn, "SELECT amount, transaction_type FROM transactions WHERE id = $tid AND user_id = $uid LIMIT 1");
    if ($tx = mysqli_fetch_assoc($txQ)) {
        $is_debit = in_array($tx['transaction_type'], ['Transfer']);
        $adjustment = $is_debit ? +$tx['amount'] : -$tx['amount'];

        $new_balance = $user['account_balance'] + $adjustment;
        if ($new_balance < 0) $new_balance = 0;

        mysqli_query($conn, "UPDATE users SET account_balance = $new_balance WHERE id = $uid");
        mysqli_query($conn, "DELETE FROM transactions WHERE id = $tid AND user_id = $uid");

        $delete_message = "Transaction deleted. Balance adjusted.";
        $delete_type    = "success";
    } else {
        $delete_message = "Transaction not found or not owned by user.";
        $delete_type    = "danger";
    }
}

// ────────────────────────────────────────────────
// HANDLE EDIT (same page)
if (isset($_POST['action']) && $_POST['action'] === 'edit' && isset($_POST['tid'])) {
    $tid          = (int)$_POST['tid'];
    $new_type     = trim($_POST['transaction_type'] ?? '');
    $new_amount   = floatval($_POST['amount'] ?? 0);
    $new_desc     = trim($_POST['description'] ?? '');

    $valid_types = ['Transfer','Airtime','Data','Electricity','Water','Utility'];

    if (!in_array($new_type, $valid_types) || $new_amount <= 0) {
        $edit_message = "Invalid type or amount.";
        $edit_type    = "danger";
    } else {
        $oldQ = mysqli_query($conn, "SELECT amount, transaction_type FROM transactions WHERE id = $tid AND user_id = $uid LIMIT 1");
        if ($old = mysqli_fetch_assoc($oldQ)) {
            $old_debit   = in_array($old['transaction_type'], ['Transfer']);
            $old_effect  = $old_debit ? -$old['amount'] : +$old['amount'];
            $new_effect  = in_array($new_type, ['Transfer']) ? -$new_amount : +$new_amount;

            $balance_diff = $new_effect - $old_effect;
            $new_balance  = $user['account_balance'] + $balance_diff;
            if ($new_balance < 0) $new_balance = 0;

            $stmt = $conn->prepare("UPDATE transactions SET transaction_type = ?, amount = ?, description = ? WHERE id = ? AND user_id = ?");
            $stmt->bind_param("sdsii", $new_type, $new_amount, $new_desc, $tid, $uid);
            $stmt->execute();
            $stmt->close();

            $stmt2 = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
            $stmt2->bind_param("di", $new_balance, $uid);
            $stmt2->execute();
            $stmt2->close();

            $edit_message = "Transaction updated. New balance: AED " . number_format($new_balance, 2);
            $edit_type    = "success";
        } else {
            $edit_message = "Transaction not found.";
            $edit_type    = "danger";
        }
    }
}

// ────────────────────────────────────────────────
// Fetch all transactions
$txQ = mysqli_query($conn,
    "SELECT id, transaction_type, amount, description, reference, status, created_at
     FROM transactions WHERE user_id = $uid ORDER BY created_at DESC"
);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin | User Transactions</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

    <link rel="stylesheet" href="assets/admin-transactions.css">
</head>
<body>

<div class="app">

    <!-- TOP HEADER -->
    <div class="top-header">
        <a href="admin_view_user.php?uid=<?= $uid ?>" class="back-icon">
            <i class="bi bi-arrow-left"></i>
        </a>
        <div>
            <small>Admin Panel</small>
            <h4>Transaction History</h4>
        </div>
        <i class="bi bi-shield-check"></i>
    </div>

    <!-- MESSAGES -->
    <?php if (isset($delete_message)): ?>
    <div class="container mt-3 px-4">
        <div class="alert alert-<?= $delete_type ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($delete_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    </div>
    <?php endif; ?>

    <?php if (isset($edit_message)): ?>
    <div class="container mt-3 px-4">
        <div class="alert alert-<?= $edit_type ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($edit_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    </div>
    <?php endif; ?>

    <!-- USER INFO CARD -->
    <div class="card mb-4">
        <div class="card-body d-flex align-items-center">
            <i class="bi bi-person-circle fs-1 me-3 text-primary"></i>
            <div>
                <h5 class="mb-1"><?= htmlspecialchars($user['full_name']) ?></h5>
                <small class="text-muted"><?= htmlspecialchars($user['account_number']) ?></small>
            </div>
        </div>
    </div>

    <!-- TRANSACTIONS CARD -->
    <div class="card">
        <div class="card-body">
            <h5 class="mb-4">Recent Transactions</h5>

            <?php if (mysqli_num_rows($txQ) === 0): ?>
                <p class="text-center text-muted py-5">No transactions recorded yet.</p>
            <?php else: ?>
                <div class="list-group">
                <?php while ($tx = mysqli_fetch_assoc($txQ)): ?>
                    <div class="list-group-item transaction-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <i class="bi <?= in_array($tx['transaction_type'], ['Transfer']) ? 'bi-arrow-up-right debit' : 'bi-arrow-down-left credit' ?> fs-3 me-3"></i>
                                <div>
                                    <strong><?= htmlspecialchars($tx['transaction_type']) ?></strong><br>
                                    <small class="text-muted"><?= htmlspecialchars($tx['description'] ?: '—') ?></small><br>
                                    <small class="text-muted"><?= date("d M Y • H:i", strtotime($tx['created_at'])) ?></small>
                                </div>
                            </div>

                            <div class="text-end">
                                <div class="<?= in_array($tx['transaction_type'], ['Transfer']) ? 'debit' : 'credit' ?> fw-bold fs-5">
                                    <?= in_array($tx['transaction_type'], ['Transfer']) ? '-' : '+' ?>
                                    AED <?= number_format($tx['amount'], 2) ?>
                                </div>
                                <small class="<?= $tx['status'] === 'Success' ? 'text-success' : 'text-danger' ?>">
                                    <?= $tx['status'] ?>
                                </small>
                                <div class="mt-2">
                                    <button class="btn btn-sm btn-outline-primary me-2"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editModal<?= $tx['id'] ?>">
                                        <i class="bi bi-pencil"></i> Edit
                                    </button>
                                    <form method="POST" class="d-inline" 
                                          onsubmit="return confirm('Delete this transaction? Balance will be adjusted.');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="tid" value="<?= $tx['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-trash"></i> Delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Edit Modal -->
                        <div class="modal fade" id="editModal<?= $tx['id'] ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="POST">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Edit Transaction #<?= $tx['id'] ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="action" value="edit">
                                            <input type="hidden" name="tid" value="<?= $tx['id'] ?>">

                                            <div class="mb-3">
                                                <label class="form-label">Type</label>
                                                <select name="transaction_type" class="form-select" required>
                                                    <?php
                                                    $types = ['Transfer','Airtime','Data','Electricity','Water','Utility'];
                                                    foreach ($types as $t) {
                                                        $sel = ($tx['transaction_type'] === $t) ? 'selected' : '';
                                                        echo "<option value=\"$t\" $sel>$t</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Amount (AED)</label>
                                                <input type="number" name="amount" step="0.01" 
                                                       value="<?= $tx['amount'] ?>" class="form-control" required>
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Description</label>
                                                <input type="text" name="description" 
                                                       value="<?= htmlspecialchars($tx['description'] ?? '') ?>" 
                                                       class="form-control">
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                            <button type="submit" class="btn btn-primary">Save Changes</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>