<?php
/* =========================================================
   MANAGE USER ULTRA PRO - GLOWING UI & EMOJIS
   ========================================================= */
session_start();
include("conn.php"); 

// --- 1. BACKEND UPDATE LOGIC (SAME AS BEFORE) ---
if(isset($_POST['action']) && $_POST['action'] == 'inline_update') {
    error_reporting(0);
    header('Content-Type: application/json');

    $id = mysqli_real_escape_string($conn, $_POST['id']);
    $field = $_POST['field']; 
    $value = mysqli_real_escape_string($conn, $_POST['value']);
    
    $query = "";
    switch($field) {
        case 'mobile': $query = "UPDATE shonu_subjects SET mobile = '$value' WHERE id = '$id'"; break;
        case 'password': $query = "UPDATE shonu_subjects SET pwd = '$value' WHERE id = '$id'"; break;
        case 'wallet': $query = "UPDATE shonu_kaichila SET motta = '$value' WHERE balakedara = '$id'"; break;
        case 'ifsc': $query = "UPDATE khate SET kod = '$value' WHERE byabaharkarta = '$id'"; break;
        case 'account': $query = "UPDATE khate SET khatesankhye = '$value' WHERE byabaharkarta = '$id'"; break;
        default: echo json_encode(['status'=>'error', 'msg'=>'Invalid Field']); exit;
    }

    if(mysqli_query($conn, $query)) { echo json_encode(['status'=>'success']); } 
    else { echo json_encode(['status'=>'error', 'msg'=>mysqli_error($conn)]); }
    exit();
}

// --- 2. AUTH CHECK ---
if ($_SESSION['unohs'] == null) { header("location:index.php?msg=unauthorized"); exit(); }

// --- 3. STATS LOGIC ---
$total_users = 0; $today_users = 0; $total_wallet = 0;
if($r = @mysqli_query($conn, "SELECT COUNT(*) as total FROM shonu_subjects")) { $total_users = mysqli_fetch_assoc($r)['total']; }
if($r = @mysqli_query($conn, "SELECT COUNT(*) as total FROM shonu_subjects WHERE DATE(createdate) = CURDATE()")) { $today_users = mysqli_fetch_assoc($r)['total']; }
if($r = @mysqli_query($conn, "SELECT SUM(motta) as total FROM shonu_kaichila")) { $total_wallet = mysqli_fetch_assoc($r)['total']; }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.5">
    <title>User Manager Ultra</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="css/style.css">

    <style>
        /* --- ULTRA MODERN THEME --- */
        :root {
            --bg-color: #eef2f5;
            --primary: #4e54c8;
            --secondary: #8f94fb;
            --accent: #ff4b1f;
            --success: #00b09b;
            --text-dark: #2d3436;
            --white: #ffffff;
            --glow-primary: 0 0 15px rgba(78, 84, 200, 0.5);
            --glow-success: 0 0 15px rgba(0, 176, 155, 0.4);
            --glow-danger: 0 0 15px rgba(255, 75, 31, 0.4);
        }

        body { 
            background-color: var(--bg-color); 
            font-family: 'Nunito', sans-serif; 
            color: var(--text-dark);
        }
        .content-wrapper { padding: 30px; }

        /* --- 3D STATS CARDS WITH EMOJIS --- */
        .stats-row { display: flex; gap: 25px; margin-bottom: 35px; }
        .stat-card {
            flex: 1; border-radius: 25px; padding: 30px; color: var(--white); 
            position: relative; overflow: hidden;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border: 1px solid rgba(255,255,255,0.2);
            backdrop-filter: blur(5px);
        }
        .stat-card:hover { transform: translateY(-10px) scale(1.02); box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
        
        .bg-gradient-1 { background: linear-gradient(135deg, #4e54c8, #8f94fb); } /* Blue */
        .bg-gradient-2 { background: linear-gradient(135deg, #11998e, #38ef7d); } /* Green */
        .bg-gradient-3 { background: linear-gradient(135deg, #ff416c, #ff4b2b); } /* Red */
        
        .stat-card h3 { 
            font-size: 2.8rem; font-weight: 900; margin: 10px 0 0 0; 
            text-shadow: 0 2px 4px rgba(0,0,0,0.2); 
        }
        .stat-card p { 
            font-size: 1rem; font-weight: 800; opacity: 0.9; 
            text-transform: uppercase; letter-spacing: 1.5px; margin: 0;
            display: flex; align-items: center; gap: 8px;
        }
        .stat-icon { 
            position: absolute; right: 20px; top: 50%; 
            transform: translateY(-50%) rotate(-10deg); 
            font-size: 5rem; opacity: 0.2; 
        }

        /* --- TABLE CARD GLASS STYLE --- */
        .table-card { 
            background: var(--white); border-radius: 30px; padding: 30px; 
            box-shadow: 0 10px 40px rgba(0,0,0,0.05); margin-bottom: 30px;
            border: 1px solid #fff;
        }
        .card-header-custom {
            display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;
            border-bottom: 2px dashed #eee; padding-bottom: 15px;
        }
        .table-title { 
            font-size: 1.8rem; font-weight: 900; color: var(--primary); 
            display: flex; align-items: center; gap: 15px; 
            text-transform: uppercase; letter-spacing: -0.5px;
        }

        /* --- ADVANCED DATATABLE --- */
        .table-responsive { overflow-x: auto !important; padding-bottom: 10px; }
        
        table.dataTable { width: 100% !important; border-collapse: separate; border-spacing: 0 10px; }
        
        table.dataTable thead th { 
            background: transparent; color: #666; padding: 15px; 
            font-weight: 800; font-size: 0.9rem;
            text-transform: uppercase; border-bottom: none !important;
            white-space: nowrap;
        }
        
        table.dataTable tbody tr {
            background: #fff; box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            border-radius: 15px; transition: transform 0.2s;
        }
        table.dataTable tbody tr:hover { transform: scale(1.01); background: #fcfcfc; z-index: 10; position: relative; }

        table.dataTable tbody td { 
            padding: 20px 15px; font-weight: 700; color: #444; 
            border: none; vertical-align: middle; white-space: nowrap; font-size: 0.95rem;
        }
        table.dataTable tbody td:first-child { border-radius: 15px 0 0 15px; }
        table.dataTable tbody td:last-child { border-radius: 0 15px 15px 0; }

        /* --- GLOWING INPUTS & EDIT --- */
        .editable-cell { display: flex; align-items: center; gap: 10px; }
        
        .wallet-val { 
            color: var(--success); font-weight: 900; font-size: 1.2rem; 
            background: rgba(0, 176, 155, 0.1); padding: 5px 12px; border-radius: 10px; 
            display: inline-block; min-width: 80px; text-align: center;
        }
        
        .edit-trigger { 
            cursor: pointer; color: #b2bec3; width: 35px; height: 35px; 
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            background: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.05); transition: 0.3s;
        }
        .edit-trigger:hover { 
            background: var(--primary); color: #fff; 
            transform: rotate(15deg) scale(1.1); 
            box-shadow: var(--glow-primary);
        }

        /* EDIT MODE BOX */
        .edit-mode-box { display: none; align-items: center; gap: 8px; animation: slideIn 0.3s ease; }
        @keyframes slideIn { from { opacity: 0; width: 0; } to { opacity: 1; width: auto; } }

        .modern-input { 
            width: 140px; padding: 10px 15px; border: 2px solid #e0e0e0; 
            border-radius: 12px; font-weight: 800; outline: none; transition: 0.3s; 
            background: #f9f9f9; color: var(--text-dark);
        }
        .modern-input:focus { 
            border-color: var(--primary); background: #fff;
            box-shadow: 0 0 0 4px rgba(78, 84, 200, 0.1); 
        }

        /* --- GLOWING BUTTONS --- */
        .btn-action { 
            width: 40px; height: 40px; border: none; border-radius: 12px; 
            cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 16px; 
            transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); color: white;
        }
        .btn-action:active { transform: scale(0.9); }

        .btn-save { background: var(--success); }
        .btn-save:hover { box-shadow: var(--glow-success); transform: translateY(-3px); }

        .btn-cancel { background: var(--accent); }
        .btn-cancel:hover { box-shadow: var(--glow-danger); transform: translateY(-3px); }
        
        .btn-delete {
            background: #fff0f0; color: #ff4b1f; border: 1px solid #ffdbd0; 
            width: 40px; height: 40px; border-radius: 12px; 
            display: flex; align-items: center; justify-content: center;
            font-size: 1.1rem; cursor: pointer; transition: 0.3s;
        }
        .btn-delete:hover { 
            background: var(--accent); color: white; border-color: var(--accent);
            box-shadow: var(--glow-danger); transform: rotate(5deg) scale(1.1); 
        }

        /* --- NAVBAR & UI ELEMENTS --- */
        .navbar { background: #fff !important; box-shadow: 0 4px 20px rgba(0,0,0,0.03) !important; }
        .dots-menu { font-size: 1.5rem; color: var(--text-dark); cursor: pointer; padding: 0 15px; transition: 0.3s; }
        .dots-menu:hover { color: var(--primary); transform: rotate(90deg); }
        
        .badge-id { background: #e0e7ff; color: var(--primary); padding: 5px 10px; border-radius: 8px; font-weight: 900; }
    </style>
</head>

<body>
<div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
        <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
            <h3 style="color:var(--primary); font-weight:900; margin:0; letter-spacing:-1px;">
                <i class="fa-solid fa-shield-cat"></i> ADMIN<span style="color:var(--text-dark);">PANEL</span>
            </h3>
        </div>
        <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
            <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
                <i class="fa-solid fa-bars-staggered" style="font-size:24px;"></i>
            </button>
            <ul class="navbar-nav navbar-nav-right">
                <li class="nav-item d-flex align-items-center">
                    <a class="nav-link" href="logout.php" style="font-weight:800; color:var(--text-dark); margin-right:10px; display:flex; align-items:center; gap:8px;">
                        <i class="fa-solid fa-power-off" style="color:var(--accent); background:#fff0f0; padding:8px; border-radius:50%;"></i> Logout
                    </a>
                    <i class="fa-solid fa-ellipsis-vertical dots-menu" title="More Options"></i>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container-fluid page-body-wrapper">
        <nav class="sidebar sidebar-offcanvas" id="sidebar" style="background:#fff;">
            <div class="user-profile" style="text-align:center; padding:30px 15px;">
                <div class="user-image">
                    <img src="images/faces/face28.png" style="width:80px; height:80px; border-radius:50%; border:4px solid #e0e7ff; padding:3px; box-shadow: var(--glow-primary);">
                </div>
                <div class="user-name" style="font-weight:900; font-size:1.2rem; margin-top:15px;">AB Coders</div>
                <div class="user-designation" style="color:#888; font-weight:700; font-size:0.9rem;">Super Admin 👑</div>
            </div>
            <?php include 'compass.php'; ?>
        </nav>

        <div class="main-panel">
            <div class="content-wrapper">
                
                <div class="stats-row">
                    <div class="stat-card bg-gradient-1">
                        <p><i class="fa-solid fa-users"></i> Total Users</p>
                        <h3><?php echo number_format($total_users); ?></h3>
                        <i class="fa-solid fa-user-group stat-icon"></i>
                    </div>
                    <div class="stat-card bg-gradient-2">
                        <p><i class="fa-solid fa-user-plus"></i> Joined Today</p>
                        <h3><?php echo number_format($today_users); ?></h3>
                        <i class="fa-solid fa-rocket stat-icon"></i>
                    </div>
                    <div class="stat-card bg-gradient-3">
                        <p><i class="fa-solid fa-wallet"></i> Total Wallet</p>
                        <h3>₹<?php echo number_format($total_wallet, 2); ?></h3>
                        <i class="fa-solid fa-sack-dollar stat-icon"></i>
                    </div>
                </div>

                <div class="table-card">
                    <div class="card-header-custom">
                        <span class="table-title">
                            <span style="background: var(--bg-color); padding: 10px; border-radius: 12px; color: var(--primary);">
                                <i class="fa-solid fa-database"></i>
                            </span> 
                            User Database
                        </span>
                        <span style="font-weight:700; color:#888;">Manage all users</span>
                    </div>
                    
                    <div class="table-responsive">
                        <table id="example1" class="table">
                            <thead>
                                <tr>
                                    <th>📱 Mobile</th> 
                                    <th>🆔 Own Code</th> 
                                    <th>🔗 Ref. Code</th> 
                                    <th>🔑 UID</th>
                                    <th>💰 Wallet</th> 
                                    <th>🏦 Total Dep.</th> 
                                    <th>⚡ 1st Rech.</th> 
                                    <th>📅 Date</th>
                                    <th>⚙️ Action</th> 
                                    <th>🔒 Pass</th> 
                                    <th>🏛️ IFSC</th> 
                                    <th>🔢 Acc No.</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>

            </div>
            <footer class="footer" style="background:transparent; border:none; margin-top:20px;">
                <div class="d-sm-flex justify-content-center">
                    <span class="text-muted" style="font-weight:700;">Made with ❤️ by AB Coders © 2026</span>
                </div>
            </footer>
        </div>
    </div>
</div>

<script src="vendors/base/vendor.bundle.base.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function() {
    
    // --- DATATABLE SETUP ---
    var table = $('#example1').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": { "url": "manage_user_data.php", "type": "GET" },
        "pageLength": 25,
        "ordering": false,
        "language": {
            "search": "",
            "searchPlaceholder": "🔍 Search User..."
        },
        
        // --- COLUMN MAPPING ---
        "columns": [
            // 0: Mobile
            { "data": 0, "render": function(data, type, row) { return makeInlineEdit(data, row[3], 'mobile'); } },
            // 1: Own Code
            { "data": 1 },
            // 2: Ref Code
            { "data": 2 },
            // 3: UID
            { "data": 3, "render": function(data) { return '<span class="badge-id">#'+data+'</span>'; } },

            // WALLET (Index 4)
            { "data": 4, "render": function(data, type, row) { return makeInlineEdit(data, row[3], 'wallet', true); } }, 
            
            // Total Dep (Index 5)
            { "data": 5, "render": function(data) { return data ? '₹'+data : '₹0'; } }, 

            // 1st Recharge (Index 6)
            { "data": 6, "render": function(data) { return data ? '₹'+data : '-'; } },

            // Date (Index 7)
            { "data": 7 }, 

            // Action (Custom)
            { "data": 8, "render": function(data, type, row) { return `<button class="btn-delete" onclick="deleteUser('${row[3]}')" title="Delete"><i class="fa-solid fa-trash-can"></i></button>`; } }, 
            
            // Password (Index 9)
            { "data": 9, "render": function(data, type, row) { return makeInlineEdit(data, row[3], 'password'); } }, 
            
            // IFSC (Index 10)
            { "data": 10, "render": function(data, type, row) { return makeInlineEdit(data, row[3], 'ifsc'); } }, 
            
            // ACCOUNT (Index 11)
            { "data": 11, "render": function(data, type, row) { return makeInlineEdit(data, row[3], 'account'); } } 
        ]
    });

    // --- RENDER FUNCTION (With Icons & Clean UI) ---
    function makeInlineEdit(rawValue, id, field, isWallet = false) {
        let cleanText = String(rawValue).split('<')[0].trim();
        if(cleanText === 'null' || cleanText === '') cleanText = '-';
        
        let inputValue = cleanText.replace(/,/g, '').replace('₹', '').replace('-', '');
        let styleClass = isWallet ? 'wallet-val' : 'data-text';
        let prefix = isWallet && cleanText !== '-' ? '₹' : '';

        return `
            <div class="editable-cell" id="box_${field}_${id}">
                <span class="${styleClass}">${prefix}${cleanText}</span>
                <i class="fa-solid fa-pen-to-square edit-trigger" onclick="enableEdit('${id}', '${field}')"></i>
            </div>

            <div class="edit-mode-box" id="edit_${field}_${id}">
                <input type="text" class="modern-input" id="input_${field}_${id}" value="${inputValue}">
                <button class="btn-action btn-save" onclick="saveEdit('${id}', '${field}')"><i class="fa-solid fa-check"></i></button>
                <button class="btn-action btn-cancel" onclick="cancelEdit('${id}', '${field}')"><i class="fa-solid fa-xmark"></i></button>
            </div>
        `;
    }

    // --- JS LOGIC ---
    window.enableEdit = function(id, field) { 
        $(`#box_${field}_${id}`).hide(); 
        $(`#edit_${field}_${id}`).css('display', 'flex'); 
        $(`#input_${field}_${id}`).focus(); 
    };

    window.cancelEdit = function(id, field) { 
        $(`#edit_${field}_${id}`).hide(); 
        $(`#box_${field}_${id}`).show(); 
    };

    window.saveEdit = function(id, field) {
        var newValue = $(`#input_${field}_${id}`).val();
        
        $.ajax({
            url: "manage_user.php", 
            type: "POST",
            data: { action: 'inline_update', id: id, field: field, value: newValue },
            success: function(response) {
                if(typeof response === 'string') { try { response = JSON.parse(response); } catch(e){} }

                if(response.status === 'success') {
                    let displayVal = newValue;
                    if(field === 'wallet') displayVal = '₹' + parseFloat(newValue).toLocaleString('en-IN');
                    
                    $(`#box_${field}_${id} span`).text(displayVal.replace('₹₹', '₹'));
                    cancelEdit(id, field);
                } else {
                    alert("⚠️ Error: " + (response.msg || "Update Failed"));
                }
            }
        });
    };

    window.deleteUser = function(id) {
        if(confirm("🛑 Are you sure? This will delete user permanently!")) {
            $.post("manage_userAction.php", { id: id, type: 'delete' }, function(){ table.ajax.reload(null, false); });
        }
    };
});
</script>
</body>
</html>