<?php
session_start();

$config_paths = ['config.php', 'Config.php', '../config.php', '../Config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}
if (!isset($conn) && isset($con)) $conn = $con;

$admin_user = $_SESSION['admin_user'] ?? '';
$admin_pass = $_SESSION['admin_pass'] ?? '';

if (empty($admin_user) || empty($admin_pass)) {
    header("Location: admin_login.php");
    exit;
}

$has_permission = false;
$md5_pass_sess = md5($admin_pass);

$admin_stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND (password=? OR password=?) LIMIT 1");
if ($admin_stmt) {
    $admin_stmt->bind_param("sss", $admin_user, $admin_pass, $md5_pass_sess);
    $admin_stmt->execute();
    if ($admin_stmt->get_result()->num_rows > 0) {
        $has_permission = true;
    }
    $admin_stmt->close();
}

if (!$has_permission) {
    $mod_stmt = $conn->prepare("SELECT extra_json FROM modarator_permissions WHERE username=? AND (password=? OR password=?) LIMIT 1");
    if ($mod_stmt) {
        $mod_stmt->bind_param("sss", $admin_user, $admin_pass, $md5_pass_sess);
        $mod_stmt->execute();
        $mod_res = $mod_stmt->get_result();
        if ($mod_res->num_rows > 0) {
            $mod_data = $mod_res->fetch_assoc();
            $extra_json = json_decode($mod_data['extra_json'], true);
            if (isset($extra_json['bonus_management']) && $extra_json['bonus_management'] === 'Yes') {
                $has_permission = true;
            }
        }
        $mod_stmt->close();
    }
}

if (!$has_permission) {
    die('<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>অ্যাক্সেস বাতিল</title></head><body style="margin:0;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;background:#f2f2f7;font-family:sans-serif;"><svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="#ff3b30" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><h2 style="color:#ff3b30;margin:20px 0 10px;">অ্যাক্সেস বাতিল!</h2><p style="color:#8e8e93;margin-bottom:20px;">Bonus Management পারমিশন দেওয়া হয়নি।</p><button onclick="window.location.href=\'index.php\'" style="background:#007aff;color:#fff;border:none;padding:12px 24px;border-radius:10px;font-size:15px;cursor:pointer;box-shadow: 0 4px 10px rgba(0, 122, 255, 0.2);">ড্যাশবোর্ডে ফিরে যান</button></body></html>');
}

$result = $conn->query("SELECT * FROM deposits ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Deposit Manager</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    
    <style>
        body { background: #f3f4f6; font-family: system-ui, -apple-system, sans-serif; padding: 30px 0; }
        .container { max-width: 1000px; }
        .main-card { border: none; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); overflow: hidden; background: #fff; }
        .card-header-custom { background: linear-gradient(135deg, #6366f1, #8b5cf6); padding: 20px 25px; display: flex; justify-content: space-between; align-items: center; color: #fff; }
        .card-header-custom h5 { margin: 0; font-weight: 700; }
        .btn-add { background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.4); color: #fff; border-radius: 30px; padding: 8px 20px; font-weight: 600; transition: 0.3s; }
        .btn-add:hover { background: #fff; color: #6366f1; }
        .table th { background: #f8fafc; color: #64748b; font-size: 12px; text-transform: uppercase; padding: 16px; border-bottom: 2px solid #e2e8f0; }
        .table td { padding: 16px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; font-weight: 500; }
        .table tr:hover { background: #f8fafc; }
        .badge-id { background: #f1f5f9; color: #475569; padding: 6px 10px; border-radius: 6px; font-weight: 700; }
        .badge-soft { background: #e0e7ff; color: #4f46e5; padding: 6px 14px; border-radius: 30px; font-weight: 600; font-size: 14px; }
        .badge-bonus { background: #d1fae5; color: #059669; }
        .action-btn { width: 35px; height: 35px; border-radius: 8px; border: none; display: inline-flex; align-items: center; justify-content: center; margin: 0 3px; transition: 0.2s; }
        .btn-edit { background: #fef3c7; color: #d97706; }
        .btn-delete { background: #fee2e2; color: #dc2626; }
        .btn-edit:hover { background: #fde68a; } .btn-delete:hover { background: #fecaca; }
        .spinner-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 9999; align-items: center; justify-content: center; backdrop-filter: blur(2px); }

        @media (max-width: 768px) {
            body { padding: 15px 10px; }
            .card-header-custom { flex-direction: column; gap: 15px; align-items: flex-start; border-radius: 16px 16px 0 0; }
            .btn-add { width: 100%; text-align: center; }
            .main-card { background: transparent; box-shadow: none; }
            .card-body { padding: 0 !important; margin-top: 15px; }
            .table thead { display: none; }
            .table tbody tr { display: block; background: #fff; border-radius: 12px; margin-bottom: 15px; padding: 12px 16px; box-shadow: 0 2px 10px rgba(0,0,0,0.04); border: 1px solid #e5e7eb; }
            .table tbody td { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px dashed #e2e8f0; text-align: right; border-top: none; }
            .table tbody td:last-child { border-bottom: none; padding-bottom: 0; padding-top: 15px; justify-content: flex-end; gap: 10px; }
            .table tbody td::before { content: attr(data-label); font-weight: 600; color: #64748b; font-size: 13px; text-transform: uppercase; }
        }
    </style>
</head>
<body>

<div class="spinner-overlay" id="loadingSpinner">
    <div class="spinner-border text-light" role="status"></div>
</div>

<div class="container">
    <div class="main-card">
        <div class="card-header-custom">
            <h5><i class="fas fa-crown text-warning me-2"></i> Bunasex Deposit</h5>
            <button class="btn-add" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus-circle me-1"></i> Add New
            </button>
        </div>

        <div class="card-body p-0">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Deposit Amount</th>
                        <th>Bonus</th>
                        <th>Date & Time</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <?php if ($result && $result->num_rows > 0): ?>
                        <?php while ($row = $result->fetch_assoc()): ?>
                        <tr id="row-<?php echo $row['id']; ?>">
                            <td data-label="ID"><span class="badge-id">#<?php echo $row['id']; ?></span></td>
                            <td data-label="Deposit"><span class="badge-soft"><?php echo number_format($row['deposit_amount']); ?> ৳</span></td>
                            <td data-label="Bonus"><span class="badge-soft badge-bonus">+<?php echo number_format($row['bonus_amount']); ?> ৳</span></td>
                            <td data-label="Date"><span class="text-secondary small fw-bold"><?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?></span></td>
                            <td data-label="" class="text-center">
                                <button class="action-btn btn-edit editBtn" data-id="<?php echo $row['id']; ?>" data-deposit="<?php echo $row['deposit_amount']; ?>" data-bonus="<?php echo $row['bonus_amount']; ?>" data-bs-toggle="modal" data-bs-target="#editModal"><i class="fas fa-pen"></i></button>
                                <button class="action-btn btn-delete deleteBtn" data-id="<?php echo $row['id']; ?>"><i class="fas fa-trash-alt"></i></button>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr id="emptyRow"><td colspan="5" class="text-center py-5 text-muted fw-bold border-0"><i class="fas fa-folder-open fa-3x mb-3 opacity-50"></i><br>No Deposits Found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow" style="border-radius: 16px;">
            <div class="modal-header bg-primary text-white border-0" style="border-radius: 16px 16px 0 0;">
                <h6 class="modal-title fw-bold"><i class="fas fa-plus-circle me-2"></i>Add Deposit</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label fw-bold">Deposit Amount</label>
                    <input type="number" class="form-control form-control-lg" id="addDeposit" placeholder="Amount" min="1">
                </div>
                <div>
                    <label class="form-label fw-bold">Bonus Amount</label>
                    <input type="number" class="form-control form-control-lg" id="addBonus" placeholder="Bonus" min="0">
                </div>
            </div>
            <div class="modal-footer border-0 bg-light" style="border-radius: 0 0 16px 16px;">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary px-4" id="addSubmitBtn">Save</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow" style="border-radius: 16px;">
            <div class="modal-header bg-warning text-dark border-0" style="border-radius: 16px 16px 0 0;">
                <h6 class="modal-title fw-bold"><i class="fas fa-pen me-2"></i>Edit Deposit</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" id="editId">
                <div class="mb-3">
                    <label class="form-label fw-bold">Deposit Amount</label>
                    <input type="number" class="form-control form-control-lg" id="editDeposit" min="1">
                </div>
                <div>
                    <label class="form-label fw-bold">Bonus Amount</label>
                    <input type="number" class="form-control form-control-lg" id="editBonus" min="0">
                </div>
            </div>
            <div class="modal-footer border-0 bg-light" style="border-radius: 0 0 16px 16px;">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-warning px-4 fw-bold" id="editSubmitBtn">Update</button>
            </div>
        </div>
    </div>
</div>

<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
    <div id="liveToast" class="toast border-0 shadow-sm" role="alert">
        <div class="toast-header text-white" id="toastHeader">
            <strong class="me-auto" id="toastTitle">Notice</strong>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body bg-white text-dark fw-bold" id="toastMessage"></div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
const AUTH_USER = "<?php echo addslashes($admin_user); ?>";
const AUTH_PASS = "<?php echo addslashes($admin_pass); ?>";

$(document).ready(function() {
    function showToast(msg, type='success') {
        $('#toastHeader').removeClass('bg-success bg-danger bg-warning').addClass(type === 'success' ? 'bg-success' : (type === 'warning' ? 'bg-warning text-dark' : 'bg-danger'));
        $('#toastTitle').html(type === 'success' ? '<i class="fas fa-check"></i> Success' : '<i class="fas fa-times"></i> Error');
        $('#toastMessage').text(msg);
        new bootstrap.Toast($('#liveToast')[0], {delay: 3000}).show();
    }

    function toggleLoader(show) { $('#loadingSpinner').css('display', show ? 'flex' : 'none'); }

    $('#addSubmitBtn').click(function() {
        const dep = $('#addDeposit').val(), bon = $('#addBonus').val();
        if(!dep || !bon) return showToast('Fill all fields!', 'warning');
        toggleLoader(true);
        $.post('bunasex_api.php', { username: AUTH_USER, password: AUTH_PASS, type: 'add', deposit_amount: dep, bonus_amount: bon }, res => {
            toggleLoader(false);
            if(res.status) { showToast(res.message); setTimeout(()=>location.reload(), 800); }
            else showToast(res.message, 'error');
        }).fail(() => { toggleLoader(false); showToast('Server Error', 'error'); });
    });

    $(document).on('click', '.editBtn', function() {
        $('#editId').val($(this).data('id'));
        $('#editDeposit').val($(this).data('deposit'));
        $('#editBonus').val($(this).data('bonus'));
    });

    $('#editSubmitBtn').click(function() {
        const id = $('#editId').val(), dep = $('#editDeposit').val(), bon = $('#editBonus').val();
        if(!dep || !bon) return showToast('Fill all fields!', 'warning');
        toggleLoader(true);
        $.post('bunasex_api.php', { username: AUTH_USER, password: AUTH_PASS, type: 'update', id: id, deposit_amount: dep, bonus_amount: bon }, res => {
            toggleLoader(false);
            if(res.status) { showToast(res.message); setTimeout(()=>location.reload(), 800); }
            else showToast(res.message, 'error');
        }).fail(() => { toggleLoader(false); showToast('Server Error', 'error'); });
    });

    $(document).on('click', '.deleteBtn', function() {
        if(!confirm('Delete this record?')) return;
        const id = $(this).data('id');
        toggleLoader(true);
        $.post('bunasex_api.php', { username: AUTH_USER, password: AUTH_PASS, type: 'delete', id: id }, res => {
            toggleLoader(false);
            if(res.status) {
                showToast(res.message);
                $('#row-'+id).fadeOut(300, function() { $(this).remove(); if($('#tableBody tr').length==0) location.reload(); });
            } else showToast(res.message, 'error');
        }).fail(() => { toggleLoader(false); showToast('Server Error', 'error'); });
    });
});
</script>
</body>
</html>
