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

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

// Daftar tema warna yang tersedia
$color_themes = [
    'color-1' => 'Tema Merah (Default)',
    'color-2' => 'Tema Biru',
    'color-3' => 'Tema Hijau', 
    'color-4' => 'Tema Ungu',
    'color-5' => 'Tema Oranye'
];
// [Tambahkan setelah query DESCRIBE markets]
$required_columns = ['market_name', 'result_time'];
foreach ($required_columns as $col) {
    if (!in_array($col, $columns)) {
        die("Error: Kolom $col tidak ditemukan dalam tabel markets. Silakan periksa struktur database.");
    }
}
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']) : '14:30';
    $result_end_time = isset($_POST['result_end_time']) ? sanitizeInput($_POST['result_end_time']) : '14:45';
    $color_theme = isset($_POST['color_theme']) ? sanitizeInput($_POST['color_theme']) : 'color-1';
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 1;

    // Validasi input
    if (empty($market_name)) {
        $error = 'Nama market harus diisi!';
    } elseif (empty($display_name)) {
        $error = 'Nama tampilan harus diisi!';
    } elseif (empty($result_time)) {
        $error = 'Waktu result harus diisi!';
    } elseif (empty($result_end_time)) {
        $error = 'Waktu selesai result harus diisi!';
    } else {
        try {
            // Cek apakah nama market sudah ada
            $checkStmt = $db->prepare("SELECT COUNT(*) FROM markets WHERE market_name = ?");
            $checkStmt->execute([$market_name]);
            $exists = $checkStmt->fetchColumn();

            if ($exists) {
                $error = 'Nama market sudah digunakan!';
            } else {
                // Cek struktur tabel untuk menentukan kolom yang tersedia
                $stmt = $db->query("DESCRIBE markets");
                $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                $has_display_name = in_array('display_name', $columns);
                $has_color_theme = in_array('color_theme', $columns);
                $has_display_order = in_array('display_order', $columns);
                $has_status = in_array('status', $columns);
                $has_created_at = in_array('created_at', $columns);
                $has_updated_at = in_array('updated_at', $columns);
                $has_result_end_time = in_array('result_end_time', $columns);
                
                // Build query dinamis berdasarkan kolom yang tersedia
                $query_columns = ['market_name', 'result_time'];
                $query_values = [$market_name, $result_time . ':00'];
                $query_placeholders = ['?', '?'];
                
                if ($has_display_name) {
                    $query_columns[] = 'display_name';
                    $query_values[] = $display_name;
                    $query_placeholders[] = '?';
                }
                
                if ($has_result_end_time) {
                    $query_columns[] = 'result_end_time';
                    $query_values[] = $result_end_time . ':00';
                    $query_placeholders[] = '?';
                }
                
                if ($has_color_theme) {
                    $query_columns[] = 'color_theme';
                    $query_values[] = $color_theme;
                    $query_placeholders[] = '?';
                }
                
                if ($has_display_order) {
                    $query_columns[] = 'display_order';
                    $query_values[] = $display_order;
                    $query_placeholders[] = '?';
                }
                
                if ($has_status) {
                    $query_columns[] = 'status';
                    $query_values[] = $status;
                    $query_placeholders[] = '?';
                }
                
                if ($has_created_at) {
                    $query_columns[] = 'created_at';
                    $query_values[] = date('Y-m-d H:i:s');
                    $query_placeholders[] = '?';
                }
                
                if ($has_updated_at) {
                    $query_columns[] = 'updated_at';
                    $query_values[] = date('Y-m-d H:i:s');
                    $query_placeholders[] = '?';
                }
                
                // Tambah market baru
                $query = "INSERT INTO markets (" . implode(', ', $query_columns) . ") 
                          VALUES (" . implode(', ', $query_placeholders) . ")";
                
                $stmt = $db->prepare($query);
                $stmt->execute($query_values);
                
                // Update cache
                if (function_exists('updateMarketTimesCache')) {
                    updateMarketTimesCache();
                }
                
                $_SESSION['success_message'] = 'Market berhasil ditambahkan!';
                header("Location: add_result.php");
                exit();
            }
        } catch (PDOException $e) {
            $error = 'Gagal menambah market: ' . $e->getMessage();
        }
    }
}

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

if (!empty($market_name) && !preg_match('/^[a-zA-Z0-9_]+$/', $market_name)) {
    $error = 'Nama market hanya boleh mengandung huruf, angka, dan underscore!';
} 
// Validasi waktu result
elseif (!empty($result_time) && !preg_match('/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/', $result_time)) {
    $error = 'Format waktu result tidak valid!';
}
elseif (!empty($result_end_time) && !preg_match('/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/', $result_end_time)) {
    $error = 'Format waktu selesai result tidak valid!';
}
// Validasi waktu result tidak boleh setelah waktu selesai
elseif (strtotime($result_time) >= strtotime($result_end_time)) {
    $error = 'Waktu result harus sebelum waktu selesai result!';
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Tambah Market - PAPUAPOOLS 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>
        .optional-field {
            opacity: 0.7;
        }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container mt-4">
    <div class="row">
        <div class="col-lg-10 offset-lg-1">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h4><i class="fas fa-plus-circle"></i> Tambah Market Baru</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-row">
                            <div class="form-group col-md-6">
                                <label for="market_name">Nama Market (Internal)*</label>
                                <input type="text" class="form-control" id="market_name" name="market_name" 
                                       value="<?= isset($_POST['market_name']) ? htmlspecialchars($_POST['market_name']) : '' ?>" 
                                       placeholder="Contoh: papuabarat" required>
                                <small class="form-text text-muted">Nama untuk sistem (huruf kecil, tanpa spasi)</small>
                            </div>
                            
                            <div class="form-group col-md-6">
                                <label for="display_name">Nama Tampilan*</label>
                                <input type="text" class="form-control" id="display_name" name="display_name" 
                                       value="<?= isset($_POST['display_name']) ? htmlspecialchars($_POST['display_name']) : '' ?>" 
                                       placeholder="Contoh: PAPUA BARAT" required>
                                <small class="form-text text-muted">Nama yang ditampilkan di halaman utama</small>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="result_time">Waktu Mulai Result*</label>
                                <input type="time" class="form-control" id="result_time" name="result_time" 
                                       value="<?= isset($_POST['result_time']) ? htmlspecialchars($_POST['result_time']) : '14:30' ?>" required>
                                <small class="form-text text-muted">Waktu ketika result mulai ditampilkan</small>
                            </div>
                            
                            <div class="form-group col-md-6">
                                <label for="result_end_time">Waktu Selesai Result*</label>
                                <input type="time" class="form-control" id="result_end_time" name="result_end_time" 
                                       value="<?= isset($_POST['result_end_time']) ? htmlspecialchars($_POST['result_end_time']) : '14:45' ?>" required>
                                <small class="form-text text-muted">Waktu ketika result selesai ditampilkan</small>
                            </div>
                        </div>
                        
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="color_theme">Warna Tema</label>
                                <select class="form-control" id="color_theme" name="color_theme">
                                    <?php foreach ($color_themes as $value => $label): ?>
                                        <option value="<?= $value ?>" <?= (isset($_POST['color_theme']) && $_POST['color_theme'] == $value) ? 'selected' : '' ?>>
                                            <?= $label ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group col-md-6">
                                <label for="display_order">Urutan Tampilan</label>
                                <input type="number" class="form-control" id="display_order" name="display_order" 
                                       value="<?= isset($_POST['display_order']) ? htmlspecialchars($_POST['display_order']) : '0' ?>" 
                                       min="0">
                                <small class="form-text text-muted">Angka lebih kecil = tampil lebih awal</small>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select class="form-control" id="status" name="status">
                                <option value="1" selected>Aktif</option>
                                <option value="0">Non-Aktif</option>
                            </select>
                        </div>
                        
                        <?php
                        // Cek struktur tabel untuk menampilkan info
                        try {
                            $stmt = $db->query("DESCRIBE markets");
                            $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
                            
                            $missing_columns = [];
                            if (!in_array('created_at', $columns)) $missing_columns[] = 'created_at';
                            if (!in_array('updated_at', $columns)) $missing_columns[] = 'updated_at';
                            if (!in_array('color_theme', $columns)) $missing_columns[] = 'color_theme';
                            if (!in_array('display_order', $columns)) $missing_columns[] = 'display_order';
                            if (!in_array('status', $columns)) $missing_columns[] = 'status';
                            if (!in_array('result_end_time', $columns)) $missing_columns[] = 'result_end_time';
                            
                            if (!empty($missing_columns)) {
                                echo '<div class="alert alert-warning">';
                                echo '<small><i class="fas fa-exclamation-triangle"></i> ';
                                echo 'Beberapa kolom tidak tersedia di database: ' . implode(', ', $missing_columns);
                                echo '. Sistem akan menyesuaikan secara otomatis.</small>';
                                echo '</div>';
                            }
                        } catch (Exception $e) {
                            // Tidak menampilkan error jika tidak bisa cek struktur
                        }
                        ?>
                        
                        <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Tambah 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>
</body>
</html>