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

if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST['market'] as $id => $values) {
        $start = $values['start'];
        $end = $values['end'];
        $stmt = $db->prepare("UPDATE markets SET result_time_start = ?, result_time_end = ? WHERE id = ?");
        $stmt->execute([$start, $end, $id]);
    }
    header('Location: edit_result_time.php?success=1');
    exit;
}

// Ambil semua pasaran yang ingin ditampilkan (Bandung & Bogor)
$stmt = $db->query("SELECT * FROM markets WHERE market_name IN ('Bandung', 'Bogor')");
$markets = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Result Time</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container mt-5">
    <h2 class="mb-4">Edit Result Time - Pasaran</h2>
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">Waktu result berhasil diperbarui!</div>
    <?php endif; ?>
    <form method="post">
        <?php foreach ($markets as $market): ?>
            <div class="card mb-3">
                <div class="card-header bg-dark text-white">
                    <h5><?= htmlspecialchars($market['market_name']) ?> Result Time</h5>
                </div>
                <div class="card-body">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Result Start Time</label>
                            <input type="time" name="market[<?= $market['id'] ?>][start]" class="form-control" value="<?= htmlspecialchars($market['result_time_start']) ?>">
                        </div>
                        <div class="form-group col-md-6">
                            <label>Result End Time</label>
                            <input type="time" name="market[<?= $market['id'] ?>][end]" class="form-control" value="<?= htmlspecialchars($market['result_time_end']) ?>">
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
    </form>
</div>
</body>
</html>
