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

$error = '';
$success = '';

// Ambil ID market dari URL
$market_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data market yang akan diedit
$market = [];
if ($market_id > 0) {
    $stmt = $db->prepare("SELECT * FROM markets WHERE id = ?");
    $stmt->execute([$market_id]);
    $market = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$market) {
        $_SESSION['error_message'] = 'Market tidak ditemukan!';
        header("Location: add_result.php");
        exit();
    }
} else {
    $_SESSION['error_message'] = 'ID Market tidak valid!';
    header("Location: add_result.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $market_name = isset($_POST['market_name']) ? sanitizeInput($_POST['market_name']) : '';
    $display_name = isset($_POST['display_name']) ? sanitizeInput($_POST['display_name']) : '';
    $result_time = isset($_POST['result_time']) ? sanitizeInput($_POST['result_time']) : '';
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 1;

    // Validasi input
    if (empty($market_name)) {
        $error = 'Nama market harus diisi!';
    } elseif (empty($result_time)) {
        $error = 'Waktu result harus diisi!';
    } else {
        // Gunakan display_name atau fallback ke market_name
        $display_name = !empty($display_name) ? $display_name : $market_name;
        
        try {
            // Cek apakah nama market sudah ada (kecuali untuk market ini)
            $checkStmt = $db->prepare("SELECT COUNT(*) FROM markets WHERE market_name = ? AND id != ?");
            $checkStmt->execute([$market_name, $market_id]);
            $exists = $checkStmt->fetchColumn();

            if ($exists) {
                $error = 'Nama market sudah digunakan!';
            } else {
                // Update data market
                $stmt = $db->prepare("UPDATE markets SET 
                    market_name = ?, 
                    display_name = ?,
                    result_time = ?, 
                    status = ?, 
                    updated_at = NOW()
                    WHERE id = ?");
                
                $stmt->execute([$market_name, $display_name, $result_time, $status, $market_id]);
                
                $_SESSION['success_message'] = 'Market berhasil diupdate!';
                header("Location: add_result.php");
                exit();
            }
        } catch (PDOException $e) {
            $error = 'Gagal mengupdate market: ' . $e->getMessage();
        }
    }
}

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

<!DOCTYPE html>
<html>
<head>
    <title>Edit Market - SOLO POOLS 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">
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container mt-4">
    <div class="row">
        <div class="col-lg-6 offset-lg-3">
            <div class="card">
                <div class="card-header bg-warning text-white">
                    <h4><i class="fas fa-edit"></i> Edit Market</h4>
                </div>
                <div class="card-body">
                    <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>
                    
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        
                        <div class="form-group">
                            <label for="market_name">Nama Market</label>
                            <input type="text" class="form-control" id="market_name" name="market_name" 
                                   value="<?= isset($_POST['market_name']) ? htmlspecialchars($_POST['market_name']) : htmlspecialchars($market['market_name']) ?>" required>
                        </div>
                        <div class="form-group">
                            <label for="display_name">Display Name</label>
                            <input type="text" class="form-control" id="display_name" name="display_name" 
                                   value="<?= isset($_POST['display_name']) ? htmlspecialchars($_POST['display_name']) : htmlspecialchars($market['display_name'] ?? $market['market_name']) ?>">
                            <small class="form-text text-muted">Nama yang akan ditampilkan di frontend</small>
                        </div>
                        <div class="form-group">
                            <label for="result_time">Waktu Result</label>
                            <input type="time" class="form-control" id="result_time" name="result_time" 
                                   value="<?= isset($_POST['result_time']) ? htmlspecialchars($_POST['result_time']) : substr($market['result_time'], 0, 5) ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select class="form-control" id="status" name="status">
                                <option value="1" <?= (isset($_POST['status']) && $_POST['status'] == 1) || $market['status'] == 1 ? 'selected' : '' ?>>Aktif</option>
                                <option value="0" <?= (isset($_POST['status']) && $_POST['status'] == 0) || $market['status'] == 0 ? 'selected' : '' ?>>Non-Aktif</option>
                            </select>
                        </div>
                        
                        <button type="submit" class="btn btn-warning"><i class="fas fa-save"></i> Update Market</button>
                        <a href="add_result.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Kembali</a>
                    </form>
                </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>
</body>
</html>