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

// Ambil semua market
$stmt = $db->prepare("SELECT * FROM markets ORDER BY display_order ASC, market_name ASC");
$stmt->execute();
$markets = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Proses update jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = [];
    
    // Validasi format waktu
    function isValidTime($time) {
        return preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time);
    }
    
    try {
        $db->beginTransaction();
        
        foreach ($markets as $market) {
            $market_name = $market['market_name'];
            $time_input = $_POST[$market_name . '_time'] ?? '';
            $end_time_input = $_POST[$market_name . '_end_time'] ?? '';
            
            if (!isValidTime($time_input)) {
                $errors[] = "Format waktu $market_name tidak valid";
                continue;
            }
            
            if (!isValidTime($end_time_input)) {
                $errors[] = "Format waktu akhir $market_name tidak valid";
                continue;
            }
            
            // Update waktu market
            $stmt = $db->prepare("UPDATE markets SET result_time = ?, result_end_time = ?, updated_at = NOW() WHERE market_name = ?");
            $stmt->execute([$time_input . ':00', $end_time_input . ':00', $market_name]);
        }
        
        if (empty($errors)) {
            $db->commit();
            $success = "Pengaturan waktu berhasil diperbarui";
            // Reload data markets
            $stmt = $db->prepare("SELECT * FROM markets ORDER BY display_order ASC, market_name ASC");
            $stmt->execute();
            $markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $db->rollBack();
        }
        
    } catch (Exception $e) {
        $db->rollBack();
        $errors[] = "Terjadi kesalahan: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pengaturan Waktu Result - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container { max-width: 1000px; }
        .card-header { font-weight: bold; }
    </style>
</head>
<body>
    <?php include 'navbar.php'; ?>

    <div class="container py-4">
        <h1 class="mb-4">Pengaturan Waktu Result</h1>
        
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?= htmlspecialchars($error) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        
        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <?= htmlspecialchars($success) ?>
            </div>
        <?php endif; ?>
        
        <form method="post">
            <?php 
            $color_index = 0;
            $colors = ['bg-primary', 'bg-success', 'bg-info', 'bg-warning', 'bg-danger'];
            ?>
            
            <?php foreach ($markets as $market): ?>
                <?php 
                $color_class = $colors[$color_index % count($colors)];
                $color_index++;
                ?>
                <div class="card mb-4">
                    <div class="card-header <?= $color_class ?> text-white">
                        <h5 class="mb-0"><?= htmlspecialchars($market['display_name'] ?? strtoupper($market['market_name'])) ?></h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="<?= $market['market_name'] ?>_time" class="form-label">Waktu Mulai Result</label>
                                <input type="time" class="form-control" 
                                       id="<?= $market['market_name'] ?>_time" 
                                       name="<?= $market['market_name'] ?>_time" 
                                       value="<?= substr($market['result_time'], 0, 5) ?>" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="<?= $market['market_name'] ?>_end_time" class="form-label">Waktu Selesai Result</label>
                                <input type="time" class="form-control" 
                                       id="<?= $market['market_name'] ?>_end_time" 
                                       name="<?= $market['market_name'] ?>_end_time" 
                                       value="<?= substr($market['result_end_time'] ?? '14:45:00', 0, 5) ?>" required>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            
            <div class="d-flex justify-content-between">
                <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                <a href="add_result.php" class="btn btn-secondary">Kembali</a>
            </div>
        </form>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>