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

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

require '_inc/dbconn.php';

$cust_id = $_REQUEST['account_list'] ?? $_GET['id'] ?? null;
if (!$cust_id) {
    header('location:select_transaction.php?error=no_user');
    exit;
}
$id = mysqli_real_escape_string($con, $cust_id);

$show_alert = false;
$alert_type = "";
$alert_msg = "";

// BATCH UPDATE LOGIC (Fixed for "Save All Changes")
if(isset($_POST['update_trx_all']) && isset($_POST['ids'])){
    $success_count = 0;
    foreach($_POST['ids'] as $trx_id){
        $trx_id = mysqli_real_escape_string($con, $trx_id);
        $new_status = mysqli_real_escape_string($con, $_POST['edit_status'][$trx_id]);
        $new_date   = mysqli_real_escape_string($con, $_POST['edit_date'][$trx_id]);
        $new_type   = mysqli_real_escape_string($con, $_POST['edit_type'][$trx_id]);
        $new_desc   = mysqli_real_escape_string($con, $_POST['edit_desc'][$trx_id]);
        $new_amt    = mysqli_real_escape_string($con, $_POST['edit_amount'][$trx_id]);

        $upd = mysqli_query($con, "UPDATE transactions SET 
            status='$new_status', 
            created_at='$new_date', 
            type='$new_type', 
            description='$new_desc', 
            amount='$new_amt' 
            WHERE id='$trx_id'");
        
        if($upd) $success_count++;
    }
    
    $show_alert = true;
    $alert_type = ($success_count > 0) ? "success" : "error";
    $alert_msg = ($success_count > 0) ? "Audit Ledger updated successfully!" : "No changes were saved.";
}

// FETCH DATA
$user_query = mysqli_query($con, "SELECT fullname, account_number, balance FROM users WHERE id='$id'");
$user = mysqli_fetch_assoc($user_query);
$sql = "SELECT * FROM transactions WHERE user_id='$id' ORDER BY created_at DESC";
$result = mysqli_query($con, $sql);

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

<?php 
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
        
if(!isset($_SESSION['admin_login'])) {
    header('location:adminlogin.php');
    exit;
}

require '_inc/dbconn.php';

// 1. Identify context (Selected user or current update)
$cust_id = $_REQUEST['account_list'] ?? $_GET['id'] ?? null;
$id = $cust_id ? mysqli_real_escape_string($con, $cust_id) : null;

$show_alert = false;
$alert_type = "";
$alert_msg = "";

// 2. BATCH UPDATE LOGIC
if(isset($_POST['update_trx_all']) && isset($_POST['ids'])){
    $success_count = 0;
    foreach($_POST['ids'] as $trx_id){
        $trx_id = mysqli_real_escape_string($con, $trx_id);
        $new_status = mysqli_real_escape_string($con, $_POST['edit_status'][$trx_id]);
        $new_date   = mysqli_real_escape_string($con, $_POST['edit_date'][$trx_id]);
        $new_type   = mysqli_real_escape_string($con, $_POST['edit_type'][$trx_id]);
        $new_desc   = mysqli_real_escape_string($con, $_POST['edit_desc'][$trx_id]);
        $new_amt    = mysqli_real_escape_string($con, $_POST['edit_amount'][$trx_id]);

        $upd = mysqli_query($con, "UPDATE transactions SET 
            status='$new_status', 
            created_at='$new_date', 
            type='$new_type', 
            description='$new_desc', 
            amount='$new_amt' 
            WHERE id='$trx_id'");
        
        if($upd) $success_count++;
    }
    
    $show_alert = true;
    $alert_type = ($success_count > 0) ? "success" : "error";
    $alert_msg = ($success_count > 0) ? "Ledger updated successfully!" : "No changes were saved.";
}

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

<style>
/* SELECTION CARD SPECIFIC (From your first script) */
.selection-card { background: white; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); max-width: 500px; margin: 50px auto; overflow: hidden; border: 1px solid #eee; }
.card-header-gradient { background: #121212; color: white; padding: 40px; text-align: center; }
.btn-action { width: 100%; background: #121212; color: white; padding: 15px; border-radius: 10px; border: none; font-weight: 700; cursor: pointer; text-transform: uppercase; transition: 0.3s; }
.btn-action:hover { background: #333; }

/* POPUP MODAL STYLES */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); backdrop-filter: blur(5px); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.alert-box { background: white; padding: 40px; border-radius: 20px; text-align: center; max-width: 450px; width: 90%; box-shadow: 0 25px 50px rgba(0,0,0,0.3); }
.alert-icon { font-size: 60px; margin-bottom: 15px; }
.icon-success { color: #10b981; }
.icon-error { color: #e63946; }

/* LEDGER CARD/TABLE STYLES */
.table-responsive { width: 100%; max-height: 600px; overflow-y: auto; border-radius: 16px; background: #f8fafc; padding: 10px; border: 1px solid #e2e8f0; }
.ledger-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; }
.ledger-table thead th { position: sticky; top: 0; background: #121212; color: #fff; padding: 15px; font-size: 11px; text-transform: uppercase; z-index: 10; }
.ledger-table tbody tr { background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.05); border-radius: 12px; }
.ledger-table td { padding: 12px; vertical-align: middle; border: none; }

/* INPUTS */
.inline-edit { border: 1px solid #e2e8f0; border-radius: 8px; padding: 8px; background: #f8fafc; width: 100%; font-size: 13px; }
.inline-edit:focus { border-color: #dc2626; outline: none; background: #fff; }

/* STATUS BADGES */
.badge-status { padding: 6px 12px; border-radius: 8px; font-weight: 700; font-size: 11px; text-transform: uppercase; border: none; }
.status-completed { background: #dcfce7; color: #166534; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-failed { background: #fee2e2; color: #991b1b; }

.save-all-btn { background: #121212; color: white; padding: 15px 30px; border-radius: 12px; border: none; font-weight: 700; width: 100%; margin-top: 20px; cursor: pointer; transition: 0.3s; }
.save-all-btn:hover { background: #333; transform: translateY(-2px); }

/* MOBILE CARD VIEW */
@media (max-width: 768px) {
    .ledger-table, .ledger-table thead, .ledger-table tbody, .ledger-table th, .ledger-table td, .ledger-table tr { display: block; }
    .ledger-table thead { display: none; }
    .ledger-table tbody tr { margin-bottom: 15px; padding: 15px; border: 1px solid #eee; }
    .ledger-table td { padding: 8px 0; position: relative; padding-left: 45%; text-align: left; border-bottom: 1px solid #f1f5f9; }
    .ledger-table td::before { content: attr(data-label); position: absolute; left: 0; font-weight: 700; color: #64748B; font-size: 10px; text-transform: uppercase; }
}
</style>

<?php if($show_alert): ?>
<div class="modal-overlay">
    <div class="alert-box">
        <div class="alert-icon <?php echo ($alert_type == 'success') ? 'icon-success' : 'icon-error'; ?>">
            <i class="mdi <?php echo ($alert_type == 'success') ? 'mdi-check-circle' : 'mdi-alert-circle'; ?>"></i>
        </div>
        <h2 style="font-weight: 800; color: #121212;"><?php echo ($alert_type == 'success') ? 'Success!' : 'Update Failed'; ?></h2>
        <p style="color: #64748B; margin: 15px 0;"><?php echo $alert_msg; ?></p>
        <button onclick="window.location.href='?id=<?php echo $id; ?>'" style="width:100%; padding: 12px; background: #121212; color: white; border:none; border-radius: 10px; cursor:pointer; font-weight:700;">
            Continue
        </button>
    </div>
</div>
<?php endif; ?>

<div class="main-wrapper">
    <main class="content">

        <?php if(!$id): ?>
            <div class="selection-card">
                <div class="card-header-gradient">
                    <i class="mdi mdi-account-cash mb-3" style="font-size: 3rem;"></i>
                    <h2 class="font-weight-bold mb-0">Transaction Audit</h2>
                    <p class="opacity-75 mb-0">Select an account to edit history</p>
                </div>

                <div class="card-body p-5">
                    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
                        <div class="form-group mb-4">
                            <label class="form-label" style="font-weight: 700; color: #64748B;">Search & Select Account</label>
                            <select class="form-control custom-select inline-edit" name="account_list" required>
                                <option value="" disabled selected>Choose a customer...</option>
                                <?php 
                                $sql = "SELECT id, fullname, account_number FROM users ORDER BY fullname ASC";
                                $result = mysqli_query($con, $sql);
                                while($row = mysqli_fetch_assoc($result)){
                                    echo '<option value="'.$row['id'].'">'.htmlspecialchars($row['fullname']).' ('.$row['account_number'].')</option>';
                                }
                                ?>
                            </select>
                        </div>

                        <button type="submit" class="btn-action">
                            <i class="mdi mdi-format-list-bulleted mr-2"></i> FETCH TRANSACTIONS
                        </button>
                    </form>
                </div>
            </div>

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

            <div class="welcome-banner" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
                <div>
                    <h2 style="font-weight: 800; margin:0;">Audit Ledger</h2>
                    <p style="margin:0;">Auditing: <strong><?php echo htmlspecialchars($user['fullname']); ?></strong> | <a href="<?php echo $_SERVER['PHP_SELF']; ?>" style="color: #dc2626;">Change User</a></p>
                </div>
                <div style="background: white; padding: 15px; border-radius: 15px; border: 1px solid #eee;">
                    <small style="color: #64748B; font-weight: 700; text-transform: uppercase;">Balance</small>
                    <h3 style="margin:0; color: #dc2626; font-weight: 800;">$<?php echo number_format($user['balance'], 2); ?></h3>
                </div>
            </div>

            <form action="?id=<?php echo $id; ?>" method="POST">
                <div class="table-responsive">
                    <table class="ledger-table">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Type</th>
                                <th>Narration</th>
                                <th>Amount ($)</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($result) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($result)): 
                                    $statusClass = 'status-' . strtolower($row['status']);
                                ?>
                                <tr>
                                    <input type="hidden" name="ids[]" value="<?php echo $row['id']; ?>">
                                    
                                    <td data-label="Date & Time">
                                        <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="inline-edit">
                                    </td>
                                    
                                    <td data-label="Type">
                                        <select name="edit_type[<?php echo $row['id']; ?>]" class="inline-edit" style="font-weight: 700;">
                                            <option value="credit" <?php echo ($row['type'] == 'credit') ? 'selected' : ''; ?>>↑ CREDIT</option>
                                            <option value="debit" <?php echo ($row['type'] == 'debit') ? 'selected' : ''; ?>>↓ DEBIT</option>
                                        </select>
                                    </td>
                                    
                                    <td data-label="Narration">
                                        <textarea name="edit_desc[<?php echo $row['id']; ?>]" class="inline-edit" rows="1"><?php echo htmlspecialchars($row['description']); ?></textarea>
                                    </td>
                                    
                                    <td data-label="Amount ($)">
                                        <input type="number" step="0.01" name="edit_amount[<?php echo $row['id']; ?>]" value="<?php echo $row['amount']; ?>" class="inline-edit" style="font-weight: 800;">
                                    </td>
                                    
                                    <td data-label="Status">
                                        <select name="edit_status[<?php echo $row['id']; ?>]" class="badge-status <?php echo $statusClass; ?>">
                                            <option value="completed" <?php if($row['status']=='completed') echo 'selected'; ?>>Completed</option>
                                            <option value="pending" <?php if($row['status']=='pending') echo 'selected'; ?>>Pending</option>
                                            <option value="failed" <?php if($row['status']=='failed') echo 'selected'; ?>>Failed</option>
                                        </select>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="5" style="text-align:center; padding: 50px; color: #64748B;">No transactions found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <button type="submit" name="update_trx_all" class="save-all-btn">
                    <i class="mdi mdi-content-save-all" style="margin-right: 8px;"></i> SAVE ALL LEDGER CHANGES
                </button>
            </form>
        <?php endif; ?>
    </main>
</div>

<?php include 'admin_footer.php'; ?>
