<?php 
session_start();
require '_inc/dbconn.php';

if(!isset($_SESSION['admin_login'])) { 
    header('location:adminlogin.php'); 
    exit; 
}

// --- LOGIC ---
$cust_id = $_REQUEST['account_list'] ?? $_GET['id'] ?? null;
$id = $cust_id ? mysqli_real_escape_string($con, $cust_id) : null;
$show_alert = false;

if(isset($_POST['update_trx_all']) && !empty($_POST['ids'])){
    foreach($_POST['ids'] as $trx_id){

        $trx_id = mysqli_real_escape_string($con, $trx_id);

        $status = mysqli_real_escape_string($con, $_POST['edit_status'][$trx_id] ?? '');
        $date   = mysqli_real_escape_string($con, $_POST['edit_date'][$trx_id] ?? '');
        $type   = mysqli_real_escape_string($con, $_POST['edit_type'][$trx_id] ?? '');
        $desc   = mysqli_real_escape_string($con, $_POST['edit_desc'][$trx_id] ?? '');
        $amt    = mysqli_real_escape_string($con, $_POST['edit_amount'][$trx_id] ?? 0);

        mysqli_query($con, "
            UPDATE transactions 
            SET status='$status', 
                created_at='$date', 
                type='$type', 
                description='$desc', 
                amount='$amt' 
            WHERE id='$trx_id'
        ");
    }
    $show_alert = true;
}

include 'admin_header.php';
include 'admin_navbar.php';
?>

<style>
.audit-viewport { width: 100%; max-height: 500px; overflow-y: auto; border-radius: 12px; border: 1px solid #e2e8f0; background: #fff; }
.audit-table { width: 100%; border-collapse: collapse; table-layout: fixed; }
.audit-table thead th { position: sticky; top: 0; background: #121212; color: #94a3b8; padding: 12px; font-size: 11px; text-align: left; z-index: 5; }
.audit-table td { padding: 10px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }

.audit-w-date { width: 180px; }
.audit-w-type { width: 120px; }
.audit-w-desc { width: auto; }
.audit-w-amt  { width: 130px; }
.audit-w-stat { width: 140px; }

.audit-input { border: 1px solid #e2e8f0; border-radius: 6px; padding: 8px; width: 100%; font-size: 12px; box-sizing: border-box; }
.audit-badge { padding: 8px; border-radius: 6px; font-weight: 700; font-size: 10px; text-transform: uppercase; border: none; width: 100%; }
.status-completed { background: #dcfce7; color: #166534; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-failed { background: #fee2e2; color: #991b1b; }

.audit-btn-save { background: #121212; color: white; padding: 15px; border-radius: 10px; border: none; font-weight: 700; width: 100%; cursor: pointer; margin-top: 15px; }
</style>

<div class="main-wrapper" style="padding: 20px;">

<?php if($show_alert): ?>
    <div style="background: #dcfce7; color: #166534; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
        Ledger Updated Successfully!
    </div>
<?php endif; ?>

<?php if(!$id): ?>

    <div style="max-width: 500px; margin: 50px auto; background: white; padding: 30px; border-radius: 15px; border: 1px solid #eee;">
        <h3 style="text-align: center;">Audit Selector</h3>
        <form method="POST">
            <select name="account_list" class="audit-input" style="height: 45px;" required>
                <option value="">Select User...</option>
                <?php 
                $users = mysqli_query($con, "SELECT id, fullname FROM users ORDER BY fullname ASC");
                while($u = mysqli_fetch_assoc($users)){
                    echo "<option value='".$u['id']."'>".$u['fullname']."</option>";
                }
                ?>
            </select>
            <button type="submit" class="audit-btn-save">Open Ledger</button>
        </form>
    </div>

<?php else: ?>

    <?php 
    $user = mysqli_fetch_assoc(mysqli_query($con, "SELECT fullname, balance FROM users WHERE id='$id'"));
    $trxs = mysqli_query($con, "SELECT * FROM transactions WHERE user_id='$id' ORDER BY created_at DESC");
    ?>

    <div style="background: white; padding: 20px; border-radius: 15px; border: 1px solid #eee;">
        
        <div style="display: flex; justify-content: space-between; margin-bottom: 15px;">
            <strong>User: <?php echo $user['fullname']; ?></strong>
            <strong style="color: #dc2626;">Balance: $<?php echo number_format($user['balance'], 2); ?></strong>
        </div>

        <form method="POST" action="?id=<?php echo $id; ?>">
            <div class="audit-viewport">
                <table class="audit-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Narration</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>

                    <?php while($row = mysqli_fetch_assoc($trxs)): ?>
                        <tr>
                            <input type="hidden" name="ids[]" value="<?php echo $row['id']; ?>">

                            <td>
                                <input type="datetime-local" name="edit_date[<?php echo $row['id']; ?>]" 
                                value="<?php echo date('Y-m-d\TH:i', strtotime($row['created_at'])); ?>" class="audit-input">
                            </td>

                            <td>
                                <select name="edit_type[<?php echo $row['id']; ?>]" class="audit-input">
                                    <option value="credit" <?php if($row['type']=='credit') echo 'selected'; ?>>Credit</option>
                                    <option value="debit" <?php if($row['type']=='debit') echo 'selected'; ?>>Debit</option>
                                </select>
                            </td>

                            <td>
                                <textarea name="edit_desc[<?php echo $row['id']; ?>]" class="audit-input"><?php echo htmlspecialchars($row['description']); ?></textarea>
                            </td>

                            <td>
                                <input type="number" step="0.01" name="edit_amount[<?php echo $row['id']; ?>]" value="<?php echo $row['amount'];