<?php
/* =========================================================
   USER BONUS MANAGER - FINAL FIX (SIDEBAR + JS FIXED)
   ========================================================= */

// --- 1. DEBUGGING & SESSION ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
    exit();
}
include("conn.php");

// --- 2. CONFIGURATION ---
$bonusTypes = [
    3   => "🎁 Bonus"
];

$tableNames = [
    3   => "hodike_balakedara"
];

$msg = "";
$msg_type = "";

// --- 3. HANDLE SINGLE DELETE ---
if (isset($_GET['del_id']) && isset($_GET['del_type'])) {
    $delId = intval($_GET['del_id']);
    $delType = intval($_GET['del_type']);
    if(isset($tableNames[$delType])) {
        $delTable = $tableNames[$delType];
        $delQuery = "DELETE FROM $delTable WHERE id = '$delId'";
        if(mysqli_query($conn, $delQuery)) {
            $msg = "🗑️ Record Deleted!";
            $msg_type = "success";
        }
    }
}

// --- 4. HANDLE SEND BONUS ---
if (isset($_POST['send_bonus'])) {
    $userId = intval($_POST['user_id']);
    $type = intval($_POST['type']);
    $amount = floatval($_POST['amount']);
    $remark = mysqli_real_escape_string($conn, $_POST['remark']);

    if ($userId > 0 && $type > 0 && $amount > 0 && isset($tableNames[$type])) {
        $tableName = $tableNames[$type];
        $date = date("Y-m-d H:i:s");
        $serial = "Imitator"; 

        $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE '$tableName'");
        if(mysqli_num_rows($tableCheck) > 0) {
            $stmt = $conn->prepare("INSERT INTO $tableName (userkani, price, serial, shonu, remark) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("idsss", $userId, $amount, $serial, $date, $remark);
            if ($stmt->execute()) {
                // Update Wallet
                $conn->query("UPDATE shonu_kaichila SET motta = motta + $amount WHERE balakedara = '$userId'");
                $msg = "✅ SUCCESS: Wallet Updated & History Saved!";
                $msg_type = "success";
            } else {
                $msg = "❌ SQL Error: " . $stmt->error;
                $msg_type = "error";
            }
            $stmt->close();
        } else {
            $msg = "❌ Table Not Found!";
            $msg_type = "error";
        }
    } else {
        $msg = "❌ Invalid Input!";
        $msg_type = "error";
    }
}

// --- 5. CLEAR ALL HISTORY ---
if (isset($_POST['clear_history'])) {
    foreach ($tableNames as $tbl) {
        $check = mysqli_query($conn, "SHOW TABLES LIKE '$tbl'");
        if(mysqli_num_rows($check) > 0) mysqli_query($conn, "TRUNCATE TABLE $tbl");
    }
    $msg = "🗑️ All History Cleared!";
    $msg_type = "success";
}

// --- 6. FETCH HISTORY ---
$filter_uid = isset($_POST['search_uid']) ? mysqli_real_escape_string($conn, $_POST['search_uid']) : '';
$filter_date = isset($_POST['search_date']) ? mysqli_real_escape_string($conn, $_POST['search_date']) : '';

$queries = [];
foreach ($tableNames as $typeId => $tbl) {
    $check = mysqli_query($conn, "SHOW TABLES LIKE '$tbl'");
    if(mysqli_num_rows($check) == 1) {
        $bName = $bonusTypes[$typeId];
        $q = "SELECT kani, userkani AS uid, price AS amt, shonu AS dt, remark AS msg, '$bName' AS b_type, '$typeId' as raw_type FROM $tbl WHERE 1=1";
        if (!empty($filter_uid)) { $q .= " AND userkani = '$filter_uid'"; }
        if (!empty($filter_date)) { $q .= " AND shonu LIKE '$filter_date%'"; }
        $queries[] = $q;
    }
}

$history_res = null;
if (!empty($queries)) {
    $final_query = implode(" UNION ALL ", $queries) . " ORDER BY dt DESC LIMIT 50";
    $history_res = mysqli_query($conn, $final_query);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.5">
    <title>Pro Bonus Panel</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.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>
        :root { --primary: #6c5ce7; --dark: #2d3436; --success: #00b894; --danger: #d63031; --white: #ffffff; --gray: #f1f2f6; }
        body { background-color: var(--gray); font-family: 'Poppins', sans-serif; min-width: 1200px; }
        
        .admin-card { background: var(--white); border-radius: 15px; padding: 30px; box-shadow: 0 10px 30px rgba(0,0,0,0.05); margin-bottom: 30px; border-top: 5px solid var(--primary); }
        .card-header-custom { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px dashed #eee; padding-bottom: 15px; margin-bottom: 20px; }
        .header-title { font-size: 1.5rem; font-weight: 900; color: var(--primary); text-transform: uppercase; }
        
        .modern-input, .modern-select { width: 100%; padding: 15px; border: 2px solid #dfe6e9; border-radius: 10px; font-weight: 700; outline: none; transition: 0.3s; }
        .modern-input:focus { border-color: var(--primary); background: #fdfdfd; box-shadow: 0 0 0 4px rgba(108, 92, 231, 0.1); }
        
        .btn-3d { border: none; border-radius: 10px; padding: 15px 25px; font-weight: 900; text-transform: uppercase; cursor: pointer; color: #fff; box-shadow: 0 4px 0 rgba(0,0,0,0.2); transition: 0.2s; }
        .btn-send { background: var(--primary); width: 100%; }
        .btn-filter { background: var(--dark); width: 100%; }
        .btn-clear { background: var(--danger); }
        .btn-3d:active { transform: translateY(4px); box-shadow: none; }

        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; }
        .custom-table th { background: var(--dark); color: #fff; padding: 18px; text-transform: uppercase; font-size: 0.85rem; letter-spacing: 1px; }
        .custom-table td { background: #fff; padding: 15px; font-weight: 600; border-top: 1px solid #eee; border-bottom: 1px solid #eee; }
        
        .status-badge { background: #e0fbe2; color: #00b894; padding: 5px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 800; }
        .alert-msg { padding: 15px; border-radius: 10px; font-weight: 700; text-align: center; margin-bottom: 20px; }
        .success { background: #d1fae5; color: #065f46; border: 1px solid #34d399; }
        .error { background: #fee2e2; color: #991b1b; border: 1px solid #f87171; }

        /* 3-DOT MENU */
        .action-menu { position: relative; display: inline-block; }
        .three-dots { cursor: pointer; font-size: 1.2rem; color: #b2bec3; padding: 8px; border-radius: 50%; transition: 0.3s; }
        .three-dots:hover { background: #f1f2f6; color: var(--primary); }
        .menu-dropdown { 
            display: none; position: absolute; right: 0; top: 100%; background: #fff; min-width: 140px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.15); border-radius: 10px; z-index: 100; border: 1px solid #eee;
        }
        .action-menu:hover .menu-dropdown { display: block; }
        .menu-dropdown a { display: block; padding: 12px 15px; color: var(--dark); font-size: 0.85rem; text-decoration: none; font-weight: 600; }
        .menu-dropdown a:hover { background: #f8f9fa; color: var(--primary); }
    </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" style="background:#fff;">
                <a class="navbar-brand brand-logo" href="dashboard.php"><h4 style="color:var(--primary); font-weight:900; margin:0;">BONUS<span style="color:var(--dark);">PANEL</span></h4></a>
                <a class="navbar-brand brand-logo-mini" href="dashboard.php"><img src="images/logo-mini.png" alt="logo"/></a>
            </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" style="font-size: 1.5rem; color: var(--dark);"></i>
                </button>

                <ul class="navbar-nav navbar-nav-right">
                    <li class="nav-item"><a class="nav-link" href="logout.php"><i class="fa-solid fa-power-off"></i> Logout</a></li>
                </ul>

                <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
                    <i class="fa-solid fa-bars" style="font-size: 1.5rem; color: var(--dark);"></i>
                </button>
            </div>
        </nav>

        <div class="container-fluid page-body-wrapper">
            <nav class="sidebar sidebar-offcanvas" id="sidebar" style="background:#fff;">
                <?php include 'compass.php'; ?>
            </nav>

            <div class="main-panel">
                <div class="content-wrapper">
                    
                    <div class="admin-card">
                        <div class="card-header-custom">
                            <div class="header-title"><i class="fa-solid fa-paper-plane"></i> Send Bonus</div>
                        </div>

                        <?php if($msg != "") { ?>
                            <div class="alert-msg <?php echo $msg_type; ?>"><?php echo $msg; ?></div>
                        <?php } ?>

                        <form method="post">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">User ID</label>
                                    <input type="number" name="user_id" class="modern-input" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Amount (₹)</label>
                                    <input type="number" step="0.01" name="amount" class="modern-input" required>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Type</label>
                                    <select name="type" class="modern-select" required>
                                        <option value="" disabled selected>-- Select --</option>
                                        <?php foreach ($bonusTypes as $tid => $tname) echo "<option value='$tid'>$tname</option>"; ?>
                                    </select>
                                </div>
                                <div class="col-md-12 mb-4">
                                    <label class="form-label">Remark</label>
                                    <input type="text" name="remark" class="modern-input">
                                </div>
                                <div class="col-md-12">
                                    <button type="submit" name="send_bonus" class="btn-3d btn-send">SEND & UPDATE</button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="admin-card">
                        <div class="card-header-custom">
                            <div class="header-title"><i class="fa-solid fa-clock-rotate-left"></i> History</div>
                            <form method="post" onsubmit="return confirm('Delete ALL?');">
                                <button type="submit" name="clear_history" class="btn-3d btn-clear">Clear All</button>
                            </form>
                        </div>
                        
                        <form method="post" style="background:#f8f9fa; padding:20px; border-radius:12px; margin-bottom:20px;">
                            <div class="row">
                                <div class="col-md-4"><input type="text" name="search_uid" class="modern-input" placeholder="User ID" value="<?php echo $filter_uid; ?>"></div>
                                <div class="col-md-4"><input type="date" name="search_date" class="modern-input" value="<?php echo $filter_date; ?>"></div>
                                <div class="col-md-4"><button type="submit" name="apply_filter" class="btn-3d btn-filter">Filter</button></div>
                            </div>
                        </form>

                        <div class="table-responsive">
                            <table class="custom-table">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>UID</th>
                                        <th>Amount</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                        <th style="text-align:right;">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if($history_res && mysqli_num_rows($history_res) > 0) {
                                        while($r = mysqli_fetch_assoc($history_res)) { ?>
                                    <tr>
                                        <td style="color:var(--primary); font-weight:900;"><?php echo $r['b_type']; ?></td>
                                        <td><b><?php echo $r['uid']; ?></b></td>
                                        <td style="color:var(--success); font-weight:900;">+₹<?php echo number_format($r['amt'], 2); ?></td>
                                        <td><?php echo date('d-M H:i', strtotime($r['dt'])); ?></td>
                                        <td><span class="status-badge">Success</span></td>
                                        
                                        <td style="text-align:right;">
                                            <div class="action-menu">
                                                <i class="fa-solid fa-ellipsis-vertical three-dots"></i>
                                                <div class="menu-dropdown">
                                                    <a href="?del_id=<?php echo $r['id']; ?>&del_type=<?php echo $r['raw_type']; ?>" class="delete-link" onclick="return confirm('Delete?');">
                                                        <i class="fa-solid fa-trash"></i> Delete
                                                    </a>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php } } else { echo "<tr><td colspan='6' class='text-center p-4'>No Data Found</td></tr>"; } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
    
    <script src="vendors/base/vendor.bundle.base.js"></script>
    <script src="js/off-canvas.js"></script>
    <script src="js/hoverable-collapse.js"></script>
    <script src="js/template.js"></script>
    <script src="vendors/chart.js/Chart.min.js"></script>
    <script src="vendors/jquery-bar-rating/jquery.barrating.min.js"></script>
    <script src="js/dashboard.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
    
    <script>
    
    </script>
</body>
</html>