<?php
require_once 'config.php';
checkLogin();

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

// Get filter parameter - ubah ke string untuk mencocokkan nama pasaran
$filter_market = isset($_GET['market']) ? sanitizeInput($_GET['market']) : '';

// Handle actions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('Invalid CSRF token');
    }

    // Handle delete
    if (isset($_POST['delete_id'])) {
        $id = (int)$_POST['delete_id'];
        $stmt = $db->prepare("DELETE FROM lottery_results WHERE id = ?");
        $stmt->execute([$id]);
        $_SESSION['success_message'] = 'Result deleted successfully';
        header("Location: manage_results.php");
        exit();
    }

    // Handle add/edit
    if (isset($_POST['submit'])) {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $market_id = (int)$_POST['market_id'];
        $draw_number = sanitizeInput($_POST['draw_number']);
        $draw_date = sanitizeInput($_POST['draw_date']);
        $result_time = sanitizeInput($_POST['result_time']);
        $first_prize = sanitizeInput($_POST['first_prize']);
        $second_prize = sanitizeInput($_POST['second_prize']);
        $third_prize = sanitizeInput($_POST['third_prize']);
        $starter_prize = sanitizeInput($_POST['starter_prize']);
        $consolation_prize = sanitizeInput($_POST['consolation_prize']);

        // Get market name
        $stmt = $db->prepare("SELECT market_name FROM markets WHERE id = ?");
        $stmt->execute([$market_id]);
        $market = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($id > 0) {
            // Update existing record
            $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['market_name'], $draw_number, $draw_date, $result_time,
                $first_prize, $second_prize, $third_prize,
                $starter_prize, $consolation_prize, $id
            ]);
            $message = 'Result updated successfully';
        } else {
            // Insert new record
            $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['market_name'], $draw_number, $draw_date, $result_time,
                $first_prize, $second_prize, $third_prize,
                $starter_prize, $consolation_prize
            ]);
            $message = 'Result added successfully';
        }
        
        $_SESSION['success_message'] = $message;
        header("Location: manage_results.php");
        exit();
    }
}
$sql = "
    SELECT r.*, m.market_name 
    FROM lottery_results r
    JOIN markets m ON r.market_id = m.id
";
$params = [];

if (!empty($filter_market)) {
    $sql .= " WHERE m.market_name = ?"; // Filter berdasarkan nama pasaran
    $params[] = $filter_market;
}

$sql .= " ORDER BY r.draw_date DESC, r.id DESC";

// Get filtered results
$stmt = $db->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

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


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

// Get result to edit if requested
$edit_result = [];
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $db->prepare("SELECT * FROM lottery_results WHERE id = ?");
    $stmt->execute([$id]);
    $edit_result = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Results - SOLOPOOLS Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css">
    <style>
        .form-container {
            background-color: #f8f9fa;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .prize-input {
            max-width: 100px;
        }
        .filter-container {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <h2><i class="fas fa-list"></i> Manage Lottery Results</h2>
            
            <?php if (isset($_SESSION['success_message'])): ?>
                <div class="alert alert-success"><?= $_SESSION['success_message'] ?></div>
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

<div class="filter-container">
    <form method="GET" class="row g-3 align-items-center">
        <div class="col-md-4">
            <label class="form-label">Filter by Market:</label>
            <select name="market" class="form-select">
                <option value="">All Markets</option>
                <?php foreach ($markets as $market): ?>
                    <option value="<?= htmlspecialchars($market['market_name']) ?>" 
                        <?= $filter_market == $market['market_name'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($market['market_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary mt-4">
                <i class="fas fa-filter"></i> Filter
            </button>
            <?php if (!empty($filter_market)): ?>
                <a href="manage_results.php" class="btn btn-secondary mt-4">
                    <i class="fas fa-times"></i> Clear
                </a>
            <?php endif; ?>
        </div>
    </form>
</div>
            <div class="form-container">
                <h4><?= empty($edit_result) ? 'Add New Result' : 'Edit Result' ?></h4>
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="id" value="<?= $edit_result['id'] ?? '' ?>">
                    
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label">Market</label>
                            <select name="market_id" class="form-select" required>
                                <option value="">Select Market</option>
                                <?php foreach ($markets as $market): ?>
                                    <option value="<?= $market['id'] ?>" 
                                        <?= isset($edit_result['market_id']) && $edit_result['market_id'] == $market['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($market['market_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">Draw Number</label>
                            <input type="text" name="draw_number" class="form-control" 
                                   value="<?= $edit_result['draw_number'] ?? '' ?>" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">Draw Date</label>
                            <input type="date" name="draw_date" class="form-control" 
                                   value="<?= $edit_result['draw_date'] ?? date('Y-m-d') ?>" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">Result Time</label>
                            <input type="time" name="result_time" class="form-control" 
                                   value="<?= $edit_result['result_time'] ?? '14:30' ?>" required>
                        </div>
                    </div>
                    
                    <div class="row g-3 mt-2">
                        <div class="col-md-2">
                            <label class="form-label">1st Prize</label>
                            <input type="text" name="first_prize" class="form-control prize-input" 
                                   value="<?= $edit_result['first_prize'] ?? '' ?>" 
                                   pattern="\d{4}" title="4 digits" maxlength="4" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">2nd Prize</label>
                            <input type="text" name="second_prize" class="form-control prize-input" 
                                   value="<?= $edit_result['second_prize'] ?? '' ?>" 
                                   pattern="\d{4}" title="4 digits" maxlength="4" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">3rd Prize</label>
                            <input type="text" name="third_prize" class="form-control prize-input" 
                                   value="<?= $edit_result['third_prize'] ?? '' ?>" 
                                   pattern="\d{4}" title="4 digits" maxlength="4" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">Starter Prize</label>
                            <input type="text" name="starter_prize" class="form-control prize-input" 
                                   value="<?= $edit_result['starter_prize'] ?? '' ?>" 
                                   pattern="\d{4}" title="4 digits" maxlength="4" required>
                        </div>
                        
                        <div class="col-md-2">
                            <label class="form-label">Consolation</label>
                            <input type="text" name="consolation_prize" class="form-control prize-input" 
                                   value="<?= $edit_result['consolation_prize'] ?? '' ?>" 
                                   pattern="\d{4}" title="4 digits" maxlength="4" required>
                        </div>
                    </div>
                    
                    <div class="mt-3">
                        <button type="submit" name="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> <?= empty($edit_result) ? 'Add Result' : 'Update Result' ?>
                        </button>
                        <?php if (!empty($edit_result)): ?>
                            <a href="manage_results.php" class="btn btn-secondary">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>

                       <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>Market</th>
                            <th>Draw Date</th>
                            <th>Draw No.</th>
                            <th>1st</th>
                            <th>2nd</th>
                            <th>3rd</th>
                            <th>Starter</th>
                            <th>Consolation</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($results)): ?>
                            <tr>
                                <td colspan="9" class="text-center">No results found</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($results as $result): ?>
                                <tr>
                                    <td><?= htmlspecialchars($result['market_name']) ?></td>
                                    <td><?= date('d M Y', strtotime($result['draw_date'])) ?></td>
                                    <td><?= htmlspecialchars($result['draw_number']) ?></td>
                                    <td><?= htmlspecialchars($result['first_prize']) ?></td>
                                    <td><?= htmlspecialchars($result['second_prize']) ?></td>
                                    <td><?= htmlspecialchars($result['third_prize']) ?></td>
                                    <td><?= htmlspecialchars($result['starter_prize']) ?></td>
                                    <td><?= htmlspecialchars($result['consolation_prize']) ?></td>
                                    <td>
                                        <a href="manage_results.php?edit=<?= $result['id'] ?>&market=<?= $filter_market ?>" 
                                           class="btn btn-sm btn-warning">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <form method="POST" style="display:inline;">
                                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                            <input type="hidden" name="delete_id" value="<?= $result['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-danger" 
                                                    onclick="return confirm('Are you sure to delete this result?')">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Auto-format prize inputs to 4 digits
document.querySelectorAll('.prize-input').forEach(input => {
    input.addEventListener('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '');
        if (this.value.length > 4) {
            this.value = this.value.slice(0, 4);
        }
    });
});
</script>

</body>
</html>