<?php
session_start();
require_once '../db.php'; 

// --- 1. HANDLE FORM SUBMISSIONS (FUNDING & EDITING) ---
$msg = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // FUND USER
    if (isset($_POST['action']) && $_POST['action'] === 'fund') {
        $u_id = intval($_POST['user_id']);
        $amt  = floatval($_POST['amount']);
        $type = $_POST['trans_type']; // credit or debit
        
        if ($u_id > 0 && $amt > 0) {
            // Update Balance
            $operator = ($type === 'credit') ? '+' : '-';
            $conn->query("UPDATE users SET balance = balance $operator $amt WHERE id = $u_id");
            $conn->query("UPDATE wallets SET balance = balance $operator $amt WHERE user_id = $u_id");
            
            // Log Transaction
            $ref = "ADM" . time() . rand(100,999);
            $desc = "Admin $type of N$amt";
            $conn->query("INSERT INTO transactions (user_id, reference, amount, transaction_type, status, description, created_at) VALUES ($u_id, '$ref', $amt, 'wallet_funding', 'success', '$desc', NOW())");
            
            $msg = "<div class='alert alert-success'>User $type successfully!</div>";
        }
    }

    // EDIT USER
    if (isset($_POST['action']) && $_POST['action'] === 'edit') {
        $u_id  = intval($_POST['user_id']);
        $fname = trim($_POST['first_name']);
        $lname = trim($_POST['last_name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        
        $conn->query("UPDATE users SET first_name='$fname', last_name='$lname', email='$email', phone='$phone' WHERE id=$u_id");
        $msg = "<div class='alert alert-success'>User details updated!</div>";
    }
}

// --- 2. FETCH USERS (WITH SEARCH) ---
$search = $_GET['search'] ?? '';
$sql = "SELECT * FROM users";
if ($search) {
    $sql .= " WHERE username LIKE '%$search%' OR email LIKE '%$search%' OR phone LIKE '%$search%'";
}
$sql .= " ORDER BY id DESC LIMIT 50";
$users = $conn->query($sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Manage Users - Nagarta Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* --- PREMIUM THEME --- */
        :root { 
            --primary: #2c5364; --secondary: #203a43; --accent: #00d2ff; --bg: #f4f7f6; 
            --text: #334155; --white: #ffffff; --sidebar-width: 260px;
        }
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Poppins', sans-serif; }
        body { background:var(--bg); color:var(--text); display:flex; min-height:100vh; }
        
        /* SIDEBAR */
        .sidebar { width:var(--sidebar-width); background:linear-gradient(180deg, var(--secondary), var(--primary)); color:white; position:fixed; height:100%; z-index:1000; display:flex; flex-direction:column; transition:0.3s; left:0; }
        .brand { padding:25px; text-align:center; border-bottom:1px solid rgba(255,255,255,0.1); }
        .brand img { max-height:45px; }
        .nav { padding:20px; overflow-y:auto; flex:1; }
        .nav a { display:flex; align-items:center; padding:12px 15px; color:rgba(255,255,255,0.7); text-decoration:none; margin-bottom:5px; border-radius:12px; font-weight:500; transition:0.2s; }
        .nav a:hover, .nav a.active { background:white; color:var(--primary); font-weight:600; }
        .nav i { width:30px; }

        /* MAIN */
        .main { flex:1; margin-left:var(--sidebar-width); padding:25px; width:calc(100% - var(--sidebar-width)); transition:0.3s; }
        .header { background:white; padding:15px 25px; border-radius:15px; display:flex; justify-content:space-between; align-items:center; margin-bottom:25px; box-shadow:0 5px 20px rgba(0,0,0,0.03); }
        .menu-toggle { display:none; font-size:1.4rem; cursor:pointer; color:var(--primary); }

        /* SEARCH BAR */
        .search-box { display:flex; gap:10px; background:#f1f5f9; padding:5px 10px; border-radius:10px; border:1px solid #e2e8f0; width:100%; max-width:400px; }
        .search-box input { border:none; background:transparent; outline:none; flex:1; font-size:0.9rem; }
        .search-box button { background:var(--primary); color:white; border:none; padding:8px 15px; border-radius:8px; cursor:pointer; }

        /* TABLE */
        .table-container { background:white; border-radius:15px; padding:20px; overflow-x:auto; box-shadow:0 10px 30px rgba(0,0,0,0.03); }
        table { width:100%; border-collapse:collapse; min-width:700px; }
        th, td { padding:15px; text-align:left; border-bottom:1px solid #f1f5f9; font-size:0.9rem; }
        th { background:#f8fafc; color:#64748b; font-weight:600; text-transform:uppercase; font-size:0.8rem; }
        .user-info div { font-weight:600; color:var(--primary); }
        .user-info small { color:#64748b; font-size:0.8rem; }
        .balance { font-weight:700; color:#166534; }
        
        .btn-sm { padding:6px 12px; border-radius:8px; font-size:0.8rem; border:none; cursor:pointer; color:white; margin-right:5px; }
        .btn-fund { background:#10b981; }
        .btn-edit { background:#3b82f6; }

        /* MODALS */
        .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:2000; align-items:center; justify-content:center; backdrop-filter:blur(3px); }
        .modal-content { background:white; width:95%; max-width:400px; padding:25px; border-radius:15px; animation:zoomIn 0.3s; }
        @keyframes zoomIn { from{transform:scale(0.9)} to{transform:scale(1)} }
        .form-group { margin-bottom:15px; }
        .form-group label { display:block; margin-bottom:5px; font-weight:600; font-size:0.85rem; }
        .form-control { width:100%; padding:10px; border:1px solid #cbd5e1; border-radius:8px; outline:none; }
        .btn-block { width:100%; padding:12px; background:var(--primary); color:white; border:none; border-radius:10px; font-weight:600; cursor:pointer; }
        
        .alert { padding:15px; margin-bottom:20px; border-radius:10px; }
        .alert-success { background:#dcfce7; color:#166534; border:1px solid #166534; }

        @media(max-width:991px) {
            .sidebar { left:-260px; } .sidebar.active { left:0; }
            .main { margin-left:0; width:100%; } .menu-toggle { display:block; }
        }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="brand"><img src="../assets/images/logo.png" alt="Logo"></div>
    <div class="nav">
        <a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a>
        <a href="users.php" class="active"><i class="fas fa-users"></i> Manage Users</a>
        <a href="transactions.php"><i class="fas fa-chart-line"></i> Transactions</a>
        <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<div class="main">
    <div class="header">
        <div class="menu-toggle" onclick="document.querySelector('.sidebar').classList.toggle('active')"><i class="fas fa-bars"></i></div>
        <h3>Manage Users</h3>
        <form class="search-box" method="GET">
            <input type="text" name="search" placeholder="Search username, email..." value="<?php echo htmlspecialchars($search); ?>">
            <button><i class="fas fa-search"></i></button>
        </form>
    </div>

    <?php echo $msg; ?>

    <div class="table-container">
        <table>
            <thead><tr><th>User Info</th><th>Phone</th><th>Balance</th><th>Actions</th></tr></thead>
            <tbody>
                <?php while($row = $users->fetch_assoc()): ?>
                <tr>
                    <td class="user-info">
                        <div><?php echo $row['username']; ?></div>
                        <small><?php echo $row['email']; ?></small>
                    </td>
                    <td><?php echo $row['phone']; ?></td>
                    <td class="balance">₦<?php echo number_format((float)$row['balance'], 2); ?></td>
                    <td>
                        <button class="btn-sm btn-fund" onclick="openFund(<?php echo $row['id']; ?>, '<?php echo $row['username']; ?>')">Fund</button>
                        <button class="btn-sm btn-edit" onclick="openEdit(<?php echo htmlspecialchars(json_encode($row)); ?>)">Edit</button>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="fundModal" class="modal">
    <div class="modal-content">
        <div style="display:flex;justify-content:space-between;margin-bottom:20px;">
            <h3>Fund / Debit User</h3>
            <span style="cursor:pointer;" onclick="closeModal('fundModal')">&times;</span>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="fund">
            <input type="hidden" name="user_id" id="fund_user_id">
            <p id="fund_user_name" style="margin-bottom:15px; color:#64748b;"></p>
            
            <div class="form-group">
                <label>Action Type</label>
                <select name="trans_type" class="form-control">
                    <option value="credit">Credit (Add Money)</option>
                    <option value="debit">Debit (Remove Money)</option>
                </select>
            </div>
            <div class="form-group">
                <label>Amount (₦)</label>
                <input type="number" name="amount" class="form-control" required>
            </div>
            <button class="btn-block">Process Transaction</button>
        </form>
    </div>
</div>

<div id="editModal" class="modal">
    <div class="modal-content">
        <div style="display:flex;justify-content:space-between;margin-bottom:20px;">
            <h3>Edit User Details</h3>
            <span style="cursor:pointer;" onclick="closeModal('editModal')">&times;</span>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="user_id" id="edit_user_id">
            
            <div class="form-group"><label>First Name</label><input type="text" name="first_name" id="edit_fname" class="form-control"></div>
            <div class="form-group"><label>Last Name</label><input type="text" name="last_name" id="edit_lname" class="form-control"></div>
            <div class="form-group"><label>Email</label><input type="email" name="email" id="edit_email" class="form-control"></div>
            <div class="form-group"><label>Phone</label><input type="text" name="phone" id="edit_phone" class="form-control"></div>
            
            <button class="btn-block">Save Changes</button>
        </form>
    </div>
</div>

<script>
    function closeModal(id) { document.getElementById(id).style.display='none'; }
    
    function openFund(id, name) {
        document.getElementById('fund_user_id').value = id;
        document.getElementById('fund_user_name').innerText = 'User: ' + name;
        document.getElementById('fundModal').style.display = 'flex';
    }

    function openEdit(user) {
        document.getElementById('edit_user_id').value = user.id;
        document.getElementById('edit_fname').value = user.first_name;
        document.getElementById('edit_lname').value = user.last_name;
        document.getElementById('edit_email').value = user.email;
        document.getElementById('edit_phone').value = user.phone;
        document.getElementById('editModal').style.display = 'flex';
    }
</script>
</body>
</html>