<?php
ob_start();
include_once '../koneksi.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['kode_admin'])) {
    echo '<script>alert("Harap login ulang");location.href="'.$alamat_admin.'keluar.php";</script>';
    exit;
}

/* ===================== CREATE TABLE ===================== */
mysqli_query($koneksi, "
CREATE TABLE IF NOT EXISTS tb_rolling_config (
    id INT AUTO_INCREMENT PRIMARY KEY,
    userID INT DEFAULT NULL,
    nama_pengguna_anggota VARCHAR(100),
    rate DECIMAL(10,5) NOT NULL DEFAULT 0,
    max_cap BIGINT NOT NULL DEFAULT 0,
    apply_if VARCHAR(20) NOT NULL DEFAULT 'loss',
    period VARCHAR(20) NOT NULL DEFAULT 'weekly',
    bonus_day TINYINT NOT NULL DEFAULT 1,
    active TINYINT NOT NULL DEFAULT 1,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uniq_user (userID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

mysqli_query($koneksi, "
CREATE TABLE IF NOT EXISTS cron_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    process_name VARCHAR(100),
    status VARCHAR(20),
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

/* ===================== FUNCTIONS ===================== */
function get_default_rolling_config($koneksi) {
    $q = mysqli_query($koneksi, "SELECT * FROM tb_rolling_config WHERE userID IS NULL LIMIT 1");
    return mysqli_num_rows($q) ? mysqli_fetch_assoc($q) : [
        'rate'=>0,'max_cap'=>0,'apply_if'=>'loss','period'=>'weekly','bonus_day'=>1,'active'=>1
    ];
}

function upsert_rolling_config($koneksi,$userID,$nama,$rate,$cap,$apply,$period,$bonus_day,$active){
    $userID = is_null($userID) ? 'NULL' : (int)$userID;
    $nama = mysqli_real_escape_string($koneksi,$nama);

    mysqli_query($koneksi,"
        INSERT INTO tb_rolling_config
        (userID,nama_pengguna_anggota,rate,max_cap,apply_if,period,bonus_day,active)
        VALUES ($userID,'$nama',$rate,$cap,'$apply','$period',$bonus_day,$active)
        ON DUPLICATE KEY UPDATE
        rate=$rate,max_cap=$cap,apply_if='$apply',period='$period',
        bonus_day=$bonus_day,active=$active,nama_pengguna_anggota='$nama'
    ");
    return mysqli_affected_rows($koneksi)>=0;
}

/* ===== DUMMY HITUNG BONUS ===== */
function calculate_rolling_bonus() {
    return 100000; // DUMMY
}
function apply_rolling_bonus() {
    return true; // DUMMY
}

/* ===================== HANDLE POST ===================== */
$message=''; $message_type='';

if ($_SERVER['REQUEST_METHOD']=='POST') {

    /* ===== DEFAULT ===== */
    if (isset($_POST['save_default'])) {
        $ok = upsert_rolling_config(
            $koneksi,
            null,
            'DEFAULT',
            $_POST['def_rate']/100,
            (int)$_POST['def_max_cap'],
            $_POST['def_apply_if'],
            $_POST['def_period'],
            (int)$_POST['def_bonus_day'],
            (int)$_POST['def_active']
        );
        $message = $ok ? 'Default tersimpan' : 'Gagal';
        $message_type = $ok ? 'success' : 'danger';
    }

    /* ===== OVERRIDE ===== */
    if (isset($_POST['save_override'])) {
        $cuid = (int)$_POST['ov_userID'];
        $q = mysqli_query($koneksi,"SELECT nama_pengguna_anggota FROM anggota WHERE cuid=$cuid");
        if (!mysqli_num_rows($q)) {
            $message='User tidak ditemukan';
            $message_type='danger';
        } else {
            $u = mysqli_fetch_assoc($q);
            upsert_rolling_config(
                $koneksi,
                $cuid,
                $u['nama_pengguna_anggota'],
                $_POST['ov_rate']/100,
                (int)$_POST['ov_max_cap'],
                $_POST['ov_apply_if'],
                $_POST['ov_period'],
                (int)$_POST['ov_bonus_day'],
                (int)$_POST['ov_active']
            );
            $message='Override berhasil';
            $message_type='success';
        }
    }
}

$defaultCfg = get_default_rolling_config($koneksi);
?>

<!-- Form HTML dan lainnya di sini -->




<div class="container-xxl flex-grow-1 container-p-y">
    <div class="row gy-4 mb-4">
        <div class="col-md-6">
            <div class="fw-bold fs-4 text-center text-md-start">Manajemen Turnover</div>
        </div>
        <div class="col-md-6">
            <div class="text-center text-md-end">
                <span><?php echo ucapan() . ', ' . tanggalIndonesia(date('Y-m-d'), true) . ', '; ?></span>
                <span id="jam_sekarang">Jam </span>
            </div>
        </div>
    </div>
    
    <?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
        <?php echo htmlspecialchars($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <!-- Konfigurasi Default -->
    <div class="card mb-4">
        <h5 class="card-header">Konfigurasi Bonus Rolling (Default)</h5>
        <div class="card-body">
            <form method="POST">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Rate (%)</label>
                        <input type="number" step="0.001" min="0" max="100" class="form-control" name="def_rate" value="<?php echo ($defaultCfg['rate'] * 100); ?>" required>
                        <small class="text-muted">Contoh: 0.5 = 0.5%</small>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Maksimal (Rp)</label>
                        <input type="number" min="0" class="form-control" name="def_max_cap" value="<?php echo $defaultCfg['max_cap']; ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Berdasarkan</label>
                        <select name="def_apply_if" class="form-select" required>
                            <option value="loss" <?php echo $defaultCfg['apply_if'] === 'loss' ? 'selected' : ''; ?>>Loss</option>
                            <option value="turnover" <?php echo $defaultCfg['apply_if'] === 'turnover' ? 'selected' : ''; ?>>Total Betting</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Periode</label>
                        <select name="def_period" class="form-select" required>
                            <option value="weekly" <?php echo $defaultCfg['period'] === 'weekly' ? 'selected' : ''; ?>>Mingguan</option>
                            <option value="daily" <?php echo $defaultCfg['period'] === 'daily' ? 'selected' : ''; ?>>Harian</option>
                            <option value="custom" <?php echo $defaultCfg['period'] === 'custom' ? 'selected' : ''; ?>>Custom</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Hari Bonus</label>
                        <select name="def_bonus_day" class="form-select" required>
                            <option value="0" <?php echo $defaultCfg['bonus_day'] == 0 ? 'selected' : ''; ?>>Minggu</option>
                            <option value="1" <?php echo $defaultCfg['bonus_day'] == 1 ? 'selected' : ''; ?>>Senin</option>
                            <option value="2" <?php echo $defaultCfg['bonus_day'] == 2 ? 'selected' : ''; ?>>Selasa</option>
                            <option value="3" <?php echo $defaultCfg['bonus_day'] == 3 ? 'selected' : ''; ?>>Rabu</option>
                            <option value="4" <?php echo $defaultCfg['bonus_day'] == 4 ? 'selected' : ''; ?>>Kamis</option>
                            <option value="5" <?php echo $defaultCfg['bonus_day'] == 5 ? 'selected' : ''; ?>>Jumat</option>
                            <option value="6" <?php echo $defaultCfg['bonus_day'] == 6 ? 'selected' : ''; ?>>Sabtu</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="def_active" class="form-select" required>
                            <option value="1" <?php echo $defaultCfg['active'] == 1 ? 'selected' : ''; ?>>Aktif</option>
                            <option value="0" <?php echo $defaultCfg['active'] == 0 ? 'selected' : ''; ?>>Tidak Aktif</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <button type="submit" name="save_default" class="btn btn-primary">
                            <span class="tf-icons mdi mdi-content-save me-1"></span> Simpan Konfigurasi Default
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    
    <!-- Apply Manual -->
    <div class="card mb-4">
        <h5 class="card-header">Apply Bonus Rolling Manual</h5>
        <div class="card-body">
            <form method="POST" id="form-apply-bonus">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Target</label>
                        <select name="ap_target" id="ap_target" class="form-select" required>
                            <option value="all">Semua Player Aktif</option>
                            <option value="user">Per Player</option>
                        </select>
                    </div>
                    <div class="col-md-3" id="ap_user_wrap" style="display:none;">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="ap_username" id="ap_username" placeholder="Masukkan username">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Periode</label>
                        <select name="ap_period" id="ap_period" class="form-select">
                            <option value="">Ikuti Konfigurasi</option>
                            <option value="daily">Harian</option>
                            <option value="weekly">Mingguan</option>
                            <option value="custom">Custom</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Provider</label>
                        <select name="ap_provider" id="ap_provider" class="form-control selectpicker">
                            <option value="">Ikuti Konfigurasi</option>
                            <option value="casino">Casino</option>
                            <option value="sports">Sports</option>
                            <option value="card">Live Games</option>
                            <option value="table">Poker</option>
                            <option value="arcade">E-Games</option>
                            <option value="lottery">Togel</option>
                        </select>
                    </div>
                    <div class="col-md-3" id="ap_custom_start" style="display:none;">
                        <label class="form-label">Tanggal Mulai</label>
                        <input type="datetime-local" name="ap_start" id="ap_start" class="form-control">
                    </div>
                    <div class="col-md-3" id="ap_custom_end" style="display:none;">
                        <label class="form-label">Tanggal Selesai</label>
                        <input type="datetime-local" name="ap_end" id="ap_end" class="form-control">
                    </div>
                    <div class="col-12">
                        <button type="button" id="btn-apply-bonus" class="btn btn-success">
                            <span class="tf-icons mdi mdi-cash-multiple me-1"></span> Apply Bonus Sekarang
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card table-responsive p-3 mb-4">
        <?php
        $anggota = mysqli_query($koneksi, "SELECT * FROM anggota ORDER BY tanggal_bergabung DESC");
        ?>
        <h5 class="card-header">Override Konfigurasi Per Player</h5>
        <table class="table" id="table-turnover">
            <thead>
            <tr>
                <th scope="col" class="text-center">No.</th>
                <th scope="col" class="text-center">Nama Pengguna</th>
                <th scope="col" class="text-center">Turnover</th>
                <th scope="col" class="text-center">Terakhir Diperbarui</th>
                <th scope="col" class="text-center">Aksi</th>
            </tr>
            </thead>
            <tbody>
                <?php
                $nomor_anggota = 1;
                while ($data_anggota = mysqli_fetch_array($anggota)) {
                    $nama_pengguna = $data_anggota['nama_pengguna_anggota'];
                    $turnover_amount = $data_anggota['turnover_amount'];
                    $last_turnover_update = $data_anggota['last_turnover_update'];

                    $formatted_last_update = 'Belum ada';
                    if (!empty($last_turnover_update)) {
                        $datetime = new DateTime($last_turnover_update);
                        $formatted_last_update = $datetime->format('Y-m-d H:i:s');
                    }
                ?>
                    <tr>
                        <th scope="row" class="text-center"><?php echo $nomor_anggota++; ?></th>
                        <td class="text-center"><?php echo htmlspecialchars($nama_pengguna); ?></td>
                        <td class="text-center"><?php echo 'Rp.' . number_format($turnover_amount, 0, ',', '.'); ?></td>
                        <td class="text-center"><?php echo htmlspecialchars($formatted_last_update); ?></td>
                        <td class="text-center">
                            <a href="<?php echo $alamat_admin . 'ubah_turnover.php?nama=' . urlencode($nama_pengguna); ?>" class="btn btn-sm btn-primary waves-effect waves-light" aria-label="Ubah Turnover">
                                <span class="tf-icons mdi mdi-cog me-1"></span> Ubah
                            </a>
                        </td>
                    </tr>
                <?php
                }
                ?>
            </tbody>
        </table>
    </div>

    <div class="card table-responsive p-3">
        <h5 class="card-header">Status Cronjob Turnover</h5>
        <?php
        $logs = mysqli_query($koneksi, "SELECT * FROM cron_log WHERE process_name = 'update_turnover' ORDER BY created_at DESC");
        ?>
        <table class="table" id="table-log">
            <thead>
                <tr>
                    <th scope="col" class="text-center">Waktu</th>
                    <th scope="col" class="text-center">Status</th>
                    <th scope="col" class="text-center">Pesan</th>
                </tr>
            </thead>
            <tbody>
                <?php
                while ($log = mysqli_fetch_array($logs)) {
                    $status_class = '';
                    if ($log['status'] == 'ERROR') $status_class = 'text-danger';
                    else if ($log['status'] == 'SUCCESS') $status_class = 'text-success';
                    else $status_class = 'text-info';
                ?>
                    <tr>
                        <td class="text-center"><?php echo htmlspecialchars($log['created_at']); ?></td>
                        <td class="text-center <?php echo $status_class; ?>"><?php echo htmlspecialchars($log['status']); ?></td>
                        <td><?php echo htmlspecialchars($log['message']); ?></td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<script src="assets/vendor/libs/jquery/jquery.js"></script>
<script src="https://cdn.datatables.net/2.0.3/js/dataTables.js"></script>
<script>
$(document).ready(function() {
    // Inisialisasi DataTables
    $('#table-turnover').DataTable();
    $('#table-log').DataTable();

    // Tampilkan atau sembunyikan input Username berdasarkan target
    function toggleUserInput() {
        var target = $('#ap_target').val();
        if (target === 'user') {
            $('#ap_user_wrap').show();
            $('#ap_username').attr('required', true);
        } else {
            $('#ap_user_wrap').hide();
            $('#ap_username').removeAttr('required');
        }
    }

    // Tampilkan atau sembunyikan input tanggal jika periode adalah custom
    function toggleCustomDates() {
        var period = $('#ap_period').val();
        if (period === 'custom') {
            $('#ap_custom_start').show();
            $('#ap_custom_end').show();
            $('#ap_start').attr('required', true);
            $('#ap_end').attr('required', true);
        } else {
            $('#ap_custom_start').hide();
            $('#ap_custom_end').hide();
            $('#ap_start').removeAttr('required');
            $('#ap_end').removeAttr('required');
        }
    }

    // Event change target
    $('#ap_target').change(function() {
        toggleUserInput();
    });

    // Event change periode
    $('#ap_period').change(function() {
        toggleCustomDates();
    });

    // Handler untuk Apply Bonus (tanpa backend, langsung sukses)
    $('#btn-apply-bonus').click(function(e) {
        e.preventDefault();
        
        var target = $('#ap_target').val();
        var username = $('#ap_username').val();
        var period = $('#ap_period').val();
        var provider = $('#ap_provider').val();
        
        // Validasi jika target per player
        if (target === 'user' && !username) {
            alert('Harap masukkan username!');
            return;
        }
        
        // Validasi jika periode custom
        if (period === 'custom') {
            var start = $('#ap_start').val();
            var end = $('#ap_end').val();
            if (!start || !end) {
                alert('Harap isi tanggal mulai dan selesai untuk periode custom!');
                return;
            }
        }
        
        // Tampilkan pesan sukses
        var message = '';
        if (target === 'all') {
            message = 'Bonus rolling berhasil di-apply ke semua player aktif!';
        } else {
            message = 'Bonus rolling berhasil di-apply untuk username: ' + username;
        }
        
        alert(message);
        
        // Reset form
        $('#form-apply-bonus')[0].reset();
        toggleUserInput();
        toggleCustomDates();
    });

    // Panggil fungsi saat halaman siap
    toggleUserInput();
    toggleCustomDates();
});
</script>