<?php
require_once 'config.php';
checkLogin();
$error = '';
$success = '';
$selected_market = isset($_GET['pasaran']) ? $_GET['pasaran'] : '';
$edit_mode = isset($_GET['edit_id']);
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = 10; // Max 10 baris per halaman
$offset = ($page - 1) * $per_page;

// Filter tanggal (tahun, bulan, hari)
$filter_year  = isset($_GET['tahun']) ? (int)$_GET['tahun'] : 0;
$filter_month = isset($_GET['bulan']) ? (int)$_GET['bulan'] : 0;
$filter_day   = isset($_GET['hari'])  ? (int)$_GET['hari']  : 0;

// Validasi filter
if ($filter_year < 2000 || $filter_year > 2100) $filter_year = 0;
if ($filter_month < 1 || $filter_month > 12) $filter_month = 0;
if ($filter_day < 1 || $filter_day > 31) $filter_day = 0;

// Get market list
$markets = $db->query("SELECT * FROM markets ORDER BY market_name")->fetchAll(PDO::FETCH_ASSOC);

// Jika dalam mode edit, ambil data yang akan diedit
$edit_data = [];
if ($edit_mode) {
    $edit_id = sanitizeInput($_GET['edit_id']);
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
   
    if ($edit_data) {
        $selected_market = $edit_data['market'];
    }
}

$market_history = [];
$last_draw_number = '0000';
$total_rows = 0;
$total_pages = 1;
$available_years = [];

if ($selected_market) {
    try {
        // Ambil daftar tahun yang tersedia untuk dropdown filter
        $yearStmt = $db->prepare("SELECT DISTINCT YEAR(draw_date) AS y FROM lottery_results WHERE market = ? ORDER BY y DESC");
        $yearStmt->execute([$selected_market]);
        $available_years = $yearStmt->fetchAll(PDO::FETCH_COLUMN);

        // Bangun WHERE clause dinamis berdasarkan filter
        $where = "market = ?";
        $params = [$selected_market];

        if ($filter_year > 0) {
            $where .= " AND YEAR(draw_date) = ?";
            $params[] = $filter_year;
        }
        if ($filter_month > 0) {
            $where .= " AND MONTH(draw_date) = ?";
            $params[] = $filter_month;
        }
        if ($filter_day > 0) {
            $where .= " AND DAY(draw_date) = ?";
            $params[] = $filter_day;
        }

        // Hitung total data untuk pagination (dengan filter)
        $countStmt = $db->prepare("SELECT COUNT(*) FROM lottery_results WHERE $where");
        $countStmt->execute($params);
        $total_rows = (int)$countStmt->fetchColumn();
        $total_pages = max(1, ceil($total_rows / $per_page));

        // Pastikan page tidak melebihi total pages
        if ($page > $total_pages) {
            $page = $total_pages;
            $offset = ($page - 1) * $per_page;
        }

        // Ambil data history dengan LIMIT dan OFFSET + filter
        $stmt = $db->prepare("SELECT * FROM lottery_results WHERE $where ORDER BY draw_date DESC, draw_number DESC LIMIT ? OFFSET ?");
        $bindIndex = 1;
        foreach ($params as $p) {
            $stmt->bindValue($bindIndex++, $p);
        }
        $stmt->bindValue($bindIndex++, $per_page, PDO::PARAM_INT);
        $stmt->bindValue($bindIndex, $offset, PDO::PARAM_INT);
        $stmt->execute();
        $market_history = $stmt->fetchAll(PDO::FETCH_ASSOC);
       
        // Ambil draw number terakhir untuk generate otomatis (selalu dari data terbaru, tanpa filter)
        if (!$edit_mode) {
            $lastStmt = $db->prepare("SELECT draw_number FROM lottery_results WHERE market = ? ORDER BY draw_date DESC, draw_number DESC LIMIT 1");
            $lastStmt->execute([$selected_market]);
            $last_draw = $lastStmt->fetch(PDO::FETCH_ASSOC);
           
            if ($last_draw) {
                $last_draw_number = $last_draw['draw_number'];
                $next_draw_number = str_pad((intval($last_draw_number) + 1), 4, '0', STR_PAD_LEFT);
            } else {
                $next_draw_number = '0001';
            }
        }
    } catch (Exception $e) {
        $market_history = [];
        $next_draw_number = '0001';
        $total_rows = 0;
        $total_pages = 1;
    }
}

// Helper: bangun query string filter agar pagination tetap membawa filter
function buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, $page = null) {
    $q = 'pasaran=' . urlencode($selected_market);
    if ($filter_year > 0)  $q .= '&tahun=' . $filter_year;
    if ($filter_month > 0) $q .= '&bulan=' . $filter_month;
    if ($filter_day > 0)   $q .= '&hari=' . $filter_day;
    if ($page !== null)    $q .= '&page=' . $page;
    return $q;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Pastikan semua field ada dalam $_POST sebelum diakses
    $market_id = isset($_POST['market_id']) ? (int)$_POST['market_id'] : 0;
    $draw_number = isset($_POST['draw_number']) ? sanitizeInput($_POST['draw_number']) : '';
    $draw_date = isset($_POST['draw_date']) ? sanitizeInput($_POST['draw_date']) : '';
    $result_time = isset($_POST['result_time']) ? sanitizeInput($_POST['result_time']) : '14:30';
    $first_prize = isset($_POST['first_prize']) ? sanitizeInput($_POST['first_prize']) : '';
    $second_prize = isset($_POST['second_prize']) ? sanitizeInput($_POST['second_prize']) : '';
    $third_prize = isset($_POST['third_prize']) ? sanitizeInput($_POST['third_prize']) : '';
    $starter_prize = isset($_POST['starter_prize']) ? sanitizeInput($_POST['starter_prize']) : '';
    $consolation_prize = isset($_POST['consolation_prize']) ? sanitizeInput($_POST['consolation_prize']) : '';
    
    // Validasi semua field
    if ($market_id === 0) {
        $error = 'Market harus dipilih!';
    } elseif (empty($draw_number)) {
        $error = 'Draw number harus diisi!';
    } elseif (empty($draw_date)) {
        $error = 'Draw date harus diisi!';
    } elseif (empty($result_time)) {
        $error = 'Result time harus diisi!';
    } elseif (!preg_match('/^\d{4}$/', $first_prize)) {
        $error = '1st Prize harus 4 digit angka!';
    } elseif (!preg_match('/^\d{4}$/', $second_prize)) {
        $error = '2nd Prize harus 4 digit angka!';
    } elseif (!preg_match('/^\d{4}$/', $third_prize)) {
        $error = '3rd Prize harus 4 digit angka!';
    } elseif (!preg_match('/^\d{4}$/', $starter_prize)) {
        $error = 'Starter Prize harus 4 digit angka!';
    } elseif (!preg_match('/^\d{4}$/', $consolation_prize)) {
        $error = 'Consolation Prize harus 4 digit angka!';
    } else {
        // Validasi market_id
        $valid_market = false;
        foreach ($markets as $market) {
            if ($market['id'] == $market_id) {
                $valid_market = true;
                $market_name = $market['market_name'];
                break;
            }
        }
        if (!$valid_market) {
            $error = 'Invalid market selected!';
        } else {
            try {
                if ($edit_mode && isset($_POST['edit_id'])) {
                    // Mode edit - update record yang ada
                    $edit_id = (int)$_POST['edit_id'];

                    // Cek duplikat: market + draw_number + tanggal (kecuali record yang sedang diedit)
                    $checkStmt = $db->prepare("SELECT COUNT(*) FROM lottery_results
                                              WHERE market_id = ? AND draw_number = ? AND draw_date = ? AND id != ?");
                    $checkStmt->execute([$market_id, $draw_number, $draw_date, $edit_id]);
                    $exists = $checkStmt->fetchColumn();

                    if ($exists) {
                        $error = 'Result dengan Draw Number ' . htmlspecialchars($draw_number) . ' pada tanggal ' . htmlspecialchars($draw_date) . ' sudah ada!';
                    } else {
                        $stmt = $db->prepare("UPDATE lottery_results SET
                            market_id = ?, market = ?, draw_number = ?, draw_date = ?, result_time = ?,
                            first_prize = ?, second_prize = ?, third_prize = ?,
                            starter_prize = ?, consolation_prize = ?, updated_at = NOW()
                            WHERE id = ?");
                       
                        $stmt->execute([
                            $market_id, $market_name, $draw_number, $draw_date, $result_time,
                            $first_prize, $second_prize, $third_prize,
                            $starter_prize, $consolation_prize, $edit_id
                        ]);
                       
                        $_SESSION['success_message'] = 'Result updated successfully!';
                    }
                } else {
                    // Mode tambah - izinkan tanggal sama, asalkan draw_number berbeda
                    // Hanya tolak jika kombinasi market + draw_number + tanggal sudah ada
                    $checkStmt = $db->prepare("SELECT COUNT(*) FROM lottery_results
                                              WHERE market_id = ? AND draw_number = ? AND draw_date = ?");
                    $checkStmt->execute([$market_id, $draw_number, $draw_date]);
                    $exists = $checkStmt->fetchColumn();

                    if ($exists) {
                        $error = 'Result dengan Draw Number ' . htmlspecialchars($draw_number) . ' pada tanggal ' . htmlspecialchars($draw_date) . ' sudah ada! Ganti Draw Number untuk menambah result di tanggal yang sama.';
                    } else {
                        $stmt = $db->prepare("INSERT INTO lottery_results
                            (market_id, market, draw_number, draw_date, result_time,
                            first_prize, second_prize, third_prize,
                            starter_prize, consolation_prize, created_at)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                        $stmt->execute([
                            $market_id, $market_name, $draw_number, $draw_date, $result_time,
                            $first_prize, $second_prize, $third_prize, $starter_prize, $consolation_prize
                        ]);
                        logAdminActivity('UPDATE_RESULT', "Market: $market_name, Draw: $draw_number, Date: $draw_date");
                        $_SESSION['success_message'] = 'Result added successfully!';
                    }
                }
               
                if (empty($error)) {
                    header("Location: add_result.php?pasaran=" . urlencode($selected_market));
                    exit();
                }
            } catch (PDOException $e) {
                $error = 'Failed to ' . ($edit_mode ? 'update' : 'add') . ' result: ' . $e->getMessage();
            }
        }
    }
}

if (isset($_SESSION['success_message'])) {
    $success = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Fungsi untuk generate angka random 4 digit
function generateRandom4Digit() {
    return sprintf("%04d", rand(0, 9999));
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Add Result - SUNDAPOOLS Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
    <style>
        .generate-btn {
            margin-top: 32px;
        }
        .result-form-container {
            display: <?= ($selected_market || $edit_mode) ? 'block' : 'none' ?>;
        }
        .history-table {
            font-size: 0.9rem;
        }
        .history-table th {
            background-color: #f8f9fa;
        }
        .auto-draw-badge {
            font-size: 0.8rem;
            margin-left: 10px;
        }
        .nav-links {
            margin-bottom: 20px;
        }
        .nav-links a {
            margin-right: 15px;
        }
        .pagination-info {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .history-container {
            margin-top: 30px;
            border-top: 1px solid #dee2e6;
            padding-top: 20px;
        }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container mt-4">
    <div class="row">
        <div class="col-lg-10 offset-lg-1">
            <!-- Navigasi -->
            <div class="nav-links">
                <a href="add_result.php" class="btn btn-primary btn-sm">
                    <i class="fas fa-plus-circle"></i> Tambah Result
                </a>
                <a href="manage_markets.php" class="btn btn-success btn-sm">
                    <i class="fas fa-cog"></i> Kelola Pasaran
                </a>
            </div>
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h4><i class="fas fa-plus-circle"></i> Add New Result</h4>
                </div>
                <div class="card-body">
                    <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
                    <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
                   
                    <!-- Form Pilih Pasaran -->
                    <div class="form-group">
                        <label for="select_market">Pilih Pasaran</label>
                        <select class="form-control" id="select_market" onchange="if(this.value) window.location='add_result.php?pasaran='+this.value">
                            <option value="">-- Pilih Pasaran --</option>
                            <?php foreach ($markets as $market): ?>
                                <option value="<?= $market['market_name'] ?>" <?= ($selected_market == $market['market_name']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($market['market_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                   
                    <!-- Form Input Result -->
                    <div class="result-form-container">
                        <form method="POST" id="resultForm">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                            <?php if ($edit_mode): ?>
                                <input type="hidden" name="edit_id" value="<?= $edit_id ?>">
                            <?php endif; ?>
                           
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="market_id">Market</label>
                                    <select class="form-control" id="market_id" name="market_id" required>
                                        <option value="">-- Select Market --</option>
                                        <?php foreach ($markets as $market): ?>
                                            <option value="<?= $market['id'] ?>" <?= (isset($_POST['market_id']) && $_POST['market_id'] == $market['id']) || ($edit_mode && $edit_data['market_id'] == $market['id']) || (!$edit_mode && $selected_market == $market['market_name']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($market['market_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="draw_number">Draw Number
                                        <?php if (!$edit_mode && isset($next_draw_number)): ?>
                                        <span class="badge badge-info auto-draw-badge">Auto: <?= $next_draw_number ?></span>
                                        <?php endif; ?>
                                    </label>
                                    <input type="text" class="form-control" id="draw_number" name="draw_number"
                                           value="<?= isset($_POST['draw_number']) ? htmlspecialchars($_POST['draw_number']) : ($edit_mode ? $edit_data['draw_number'] : (isset($next_draw_number) ? $next_draw_number : '')) ?>"
                                           pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="draw_date">Draw Date</label>
                                    <input type="date" class="form-control" id="draw_date" name="draw_date"
                                           value="<?= isset($_POST['draw_date']) ? htmlspecialchars($_POST['draw_date']) : ($edit_mode ? $edit_data['draw_date'] : date('Y-m-d')) ?>" required>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="result_time">Result Time</label>
                                    <input type="time" class="form-control" id="result_time" name="result_time"
                                           value="<?= isset($_POST['result_time']) ? htmlspecialchars($_POST['result_time']) : ($edit_mode ? substr($edit_data['result_time'], 0, 5) : '14:30') ?>" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="first_prize">1st Prize</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="first_prize" name="first_prize"
                                           value="<?= isset($_POST['first_prize']) ? htmlspecialchars($_POST['first_prize']) : ($edit_mode ? $edit_data['first_prize'] : '') ?>"
                                           pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-outline-secondary generate-btn" id="generateAllBtn">
                                            <i class="fas fa-dice"></i> Generate All Random
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="second_prize">2nd Prize</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="second_prize" name="second_prize"
                                               value="<?= isset($_POST['second_prize']) ? htmlspecialchars($_POST['second_prize']) : ($edit_mode ? $edit_data['second_prize'] : '') ?>"
                                               pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary generate-single-btn" data-target="second_prize">
                                                <i class="fas fa-dice-one"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="third_prize">3rd Prize</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="third_prize" name="third_prize"
                                               value="<?= isset($_POST['third_prize']) ? htmlspecialchars($_POST['third_prize']) : ($edit_mode ? $edit_data['third_prize'] : '') ?>"
                                               pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary generate-single-btn" data-target="third_prize">
                                                <i class="fas fa-dice-one"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <label for="starter_prize">Starter Prize</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="starter_prize" name="starter_prize"
                                               value="<?= isset($_POST['starter_prize']) ? htmlspecialchars($_POST['starter_prize']) : ($edit_mode ? $edit_data['starter_prize'] : '') ?>"
                                               pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary generate-single-btn" data-target="starter_prize">
                                                <i class="fas fa-dice-one"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="consolation_prize">Consolation Prize</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="consolation_prize" name="consolation_prize"
                                               value="<?= isset($_POST['consolation_prize']) ? htmlspecialchars($_POST['consolation_prize']) : ($edit_mode ? $edit_data['consolation_prize'] : '') ?>"
                                               pattern="\d{4}" title="Harus 4 digit angka" required maxlength="4">
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary generate-single-btn" data-target="consolation_prize">
                                                <i class="fas fa-dice-one"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
                            <a href="index.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Kembali</a>
                           
                            <?php if (!$edit_mode && isset($next_draw_number)): ?>
                            <button type="button" class="btn btn-outline-info" id="autoFillBtn">
                                <i class="fas fa-magic"></i> Auto Fill from Last Draw
                            </button>
                            <?php endif; ?>
                            <?php if ($edit_mode): ?>
                            <a href="add_result.php?pasaran=<?= urlencode($selected_market) ?>" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Batal Edit
                            </a>
                            <?php endif; ?>
                        </form>
                    </div>
                    
                    <!-- History Result untuk Pasaran Terpilih -->
                    <?php if ($selected_market): ?>
                    <div class="history-container mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0">History Result: <?= htmlspecialchars($selected_market) ?></h5>
                            <?php if ($total_rows > 0): ?>
                            <span class="pagination-info">
                                Menampilkan <?= $offset + 1 ?>–<?= min($offset + $per_page, $total_rows) ?> dari <?= $total_rows ?> data
                            </span>
                            <?php endif; ?>
                        </div>

                        <!-- Form Filter Tanggal / Bulan / Tahun -->
                        <form method="GET" class="mb-3" id="filterForm">
                            <input type="hidden" name="pasaran" value="<?= htmlspecialchars($selected_market) ?>">
                            <div class="form-row align-items-end">
                                <div class="form-group col-md-2 col-6 mb-2">
                                    <label for="filter_tahun" class="small mb-1">Tahun</label>
                                    <select class="form-control form-control-sm" id="filter_tahun" name="tahun">
                                        <option value="">Semua Tahun</option>
                                        <?php foreach ($available_years as $y): ?>
                                            <option value="<?= $y ?>" <?= ($filter_year == $y) ? 'selected' : '' ?>><?= $y ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-2 col-6 mb-2">
                                    <label for="filter_bulan" class="small mb-1">Bulan</label>
                                    <select class="form-control form-control-sm" id="filter_bulan" name="bulan">
                                        <option value="">Semua Bulan</option>
                                        <?php
                                        $bulan_nama = [
                                            1 => 'Januari', 2 => 'Februari', 3 => 'Maret',
                                            4 => 'April', 5 => 'Mei', 6 => 'Juni',
                                            7 => 'Juli', 8 => 'Agustus', 9 => 'September',
                                            10 => 'Oktober', 11 => 'November', 12 => 'Desember'
                                        ];
                                        foreach ($bulan_nama as $num => $nama):
                                        ?>
                                            <option value="<?= $num ?>" <?= ($filter_month == $num) ? 'selected' : '' ?>><?= $nama ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-2 col-6 mb-2">
                                    <label for="filter_hari" class="small mb-1">Tanggal</label>
                                    <select class="form-control form-control-sm" id="filter_hari" name="hari">
                                        <option value="">Semua Tanggal</option>
                                        <?php for ($d = 1; $d <= 31; $d++): ?>
                                            <option value="<?= $d ?>" <?= ($filter_day == $d) ? 'selected' : '' ?>><?= $d ?></option>
                                        <?php endfor; ?>
                                    </select>
                                </div>
                                <div class="form-group col-md-4 col-12 mb-2">
                                    <button type="submit" class="btn btn-sm btn-primary">
                                        <i class="fas fa-search"></i> Cari
                                    </button>
                                    <?php if ($filter_year || $filter_month || $filter_day): ?>
                                    <a href="add_result.php?pasaran=<?= urlencode($selected_market) ?>" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-times"></i> Reset
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php if ($filter_year || $filter_month || $filter_day): ?>
                            <div class="mb-2">
                                <small class="text-muted">
                                    Filter aktif:
                                    <?php
                                    $filter_labels = [];
                                    if ($filter_day) $filter_labels[] = 'Tanggal ' . $filter_day;
                                    if ($filter_month) $filter_labels[] = $bulan_nama[$filter_month];
                                    if ($filter_year) $filter_labels[] = $filter_year;
                                    echo implode(' ', $filter_labels);
                                    ?>
                                </small>
                            </div>
                            <?php endif; ?>
                        </form>
                        
                        <?php if (count($market_history) > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm history-table">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Draw Date</th>
                                        <th>Draw Number</th>
                                        <th>1st Prize</th>
                                        <th>2nd Prize</th>
                                        <th>3rd Prize</th>
                                        <th>Starter</th>
                                        <th>Consolation</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($market_history as $history): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($history['draw_date']) ?></td>
                                        <td><?= htmlspecialchars($history['draw_number']) ?></td>
                                        <td><span class="badge badge-primary"><?= htmlspecialchars($history['first_prize']) ?></span></td>
                                        <td><?= htmlspecialchars($history['second_prize']) ?></td>
                                        <td><?= htmlspecialchars($history['third_prize']) ?></td>
                                        <td><?= htmlspecialchars($history['starter_prize']) ?></td>
                                        <td><?= htmlspecialchars($history['consolation_prize']) ?></td>
                                        <td>
                                            <a href="add_result.php?pasaran=<?= urlencode($selected_market) ?>&edit_id=<?= $history['id'] ?>"
                                               class="btn btn-sm btn-warning" title="Edit Result">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button class="btn btn-sm btn-danger delete-result"
                                                    data-id="<?= $history['id'] ?>"
                                                    data-draw="<?= $history['draw_number'] ?>"
                                                    title="Delete Result">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination Controls -->
                        <?php if ($total_pages > 1): ?>
                        <nav aria-label="History pagination">
                            <ul class="pagination justify-content-center mt-3">
                                <!-- Previous -->
                                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="add_result.php?<?= buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, $page - 1) ?>" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                
                                <?php
                                // Tampilkan maksimal 5 nomor halaman di sekitar halaman aktif
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                if ($start_page > 1) {
                                    echo '<li class="page-item"><a class="page-link" href="add_result.php?' . buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, 1) . '">1</a></li>';
                                    if ($start_page > 2) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                }
                                
                                for ($i = $start_page; $i <= $end_page; $i++):
                                ?>
                                <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                                    <a class="page-link" href="add_result.php?<?= buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, $i) ?>"><?= $i ?></a>
                                </li>
                                <?php endfor; ?>
                                
                                <?php
                                if ($end_page < $total_pages) {
                                    if ($end_page < $total_pages - 1) {
                                        echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                                    }
                                    echo '<li class="page-item"><a class="page-link" href="add_result.php?' . buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, $total_pages) . '">' . $total_pages . '</a></li>';
                                }
                                ?>
                                
                                <!-- Next -->
                                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="add_result.php?<?= buildFilterQuery($selected_market, $filter_year, $filter_month, $filter_day, $page + 1) ?>" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                            </ul>
                        </nav>
                        <?php endif; ?>
                        
                        <?php else: ?>
                        <div class="alert alert-info mb-0">
                            <?php if ($filter_year || $filter_month || $filter_day): ?>
                                Tidak ditemukan data history untuk filter yang dipilih.
                            <?php else: ?>
                                Belum ada history result untuk pasaran ini.
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(document).ready(function() {
    <?php if ($success): ?>
    document.getElementById("resultForm").reset();
    <?php endif; ?>
   
    // Validasi input hanya angka dan maksimal 4 digit
    $('input[pattern="\\d{4}"]').on('input', function () {
        this.value = this.value.replace(/[^0-9]/g, '');
        if (this.value.length > 4) {
            this.value = this.value.slice(0, 4);
        }
    });
   
    $(document).on('click', '.delete-result', function() {
        const id = $(this).data('id');
        const drawNumber = $(this).data('draw');
       
        if (confirm(`Apakah Anda yakin ingin menghapus result dengan draw number ${drawNumber}?`)) {
            window.location.href = 'delete_result.php?id=' + id + '&pasaran=<?= urlencode($selected_market) ?>';
        }
    });
    
    // Fungsi untuk generate angka random 4 digit
    function generateRandom4Digit() {
        return Math.floor(1000 + Math.random() * 9000).toString();
    }
   
    // Generate semua angka prize secara random
    $('#generateAllBtn').click(function() {
        $('#first_prize').val(generateRandom4Digit());
        $('#second_prize').val(generateRandom4Digit());
        $('#third_prize').val(generateRandom4Digit());
        $('#starter_prize').val(generateRandom4Digit());
        $('#consolation_prize').val(generateRandom4Digit());
    });
   
    // Generate angka untuk field tertentu saja
    $('.generate-single-btn').click(function() {
        const target = $(this).data('target');
        $('#' + target).val(generateRandom4Digit());
    });
   
    // Auto-select market
    <?php if ($selected_market): ?>
    $('#market_id').val($('#market_id option:contains("<?= $selected_market ?>")').val());
    <?php endif; ?>
   
    // Auto fill dari draw terakhir
    $('#autoFillBtn').click(function() {
        if (confirm('Auto fill akan mengisi angka dari result terakhir. Lanjutkan?')) {
            <?php
            // Ambil data terakhir secara terpisah untuk auto-fill (selalu data terbaru)
            $autoFillData = null;
            if ($selected_market) {
                $autoStmt = $db->prepare("SELECT * FROM lottery_results WHERE market = ? ORDER BY draw_date DESC, draw_number DESC LIMIT 1");
                $autoStmt->execute([$selected_market]);
                $autoFillData = $autoStmt->fetch(PDO::FETCH_ASSOC);
            }
            if ($autoFillData):
            ?>
            const lastResult = <?= json_encode($autoFillData) ?>;
           
            $('#first_prize').val(lastResult.first_prize);
            $('#second_prize').val(lastResult.second_prize);
            $('#third_prize').val(lastResult.third_prize);
            $('#starter_prize').val(lastResult.starter_prize);
            $('#consolation_prize').val(lastResult.consolation_prize);
           
            alert('Data dari draw terakhir telah diisi. Jangan lupa untuk mengubah beberapa angka!');
            <?php else: ?>
            alert('Tidak ada data history untuk auto fill.');
            <?php endif; ?>
        }
    });
});
</script>
</body>
</html>