<?php
session_start();
require_once 'config.php'; // Pastikan file config.php sudah ada
date_default_timezone_set('Asia/Jakarta');

// Cek login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

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

// Koneksi ke database
try {
    $db = new PDO('mysql:host=localhost;dbname=erniinrk_solo', 'erniinrk_solo', 'Kelentit123@');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// --- CEK & TAMBAHKAN KOLOM GAMBAR JIKA BELUM ADA ---
try {
    $stmt = $db->query("SHOW COLUMNS FROM markets LIKE 'image'");
    if ($stmt->rowCount() == 0) {
        $db->exec("ALTER TABLE markets ADD COLUMN image VARCHAR(255) NULL");
    }
} catch (PDOException $e) {
    // Abaikan error jika tabel tidak ada
}

// 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: index.php");
        exit();
    }
} else {
    $_SESSION['error_message'] = 'ID Market tidak valid!';
    header("Location: index.php");
    exit();
}

// Proses update data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $market_name = isset($_POST['market_name']) ? trim($_POST['market_name']) : '';
    $display_name = isset($_POST['display_name']) ? trim($_POST['display_name']) : '';
    $result_time = isset($_POST['result_time']) ? trim($_POST['result_time']) : '';
    $result_end_time = isset($_POST['result_end_time']) ? trim($_POST['result_end_time']) : '';
    $existing_image = isset($_POST['existing_image']) ? trim($_POST['existing_image']) : '';
    
    // Validasi input
    if (empty($market_name)) {
        $error = 'Nama market harus diisi!';
    } elseif (empty($display_name)) {
        $error = 'Display name harus diisi!';
    } elseif (empty($result_time)) {
        $error = 'Waktu Result (Jam Tutup) harus diisi!';
    } else {
        try {
            // Cek apakah nama market sudah digunakan oleh market lain
            $check_stmt = $db->prepare("SELECT id FROM markets WHERE market_name = ? AND id != ?");
            $check_stmt->execute([$market_name, $market_id]);
            if ($check_stmt->rowCount() > 0) {
                $error = 'Nama market "' . htmlspecialchars($market_name) . '" sudah digunakan!';
            } else {
                // --- LOGIKA UPLOAD GAMBAR ---
                $image_filename = $existing_image; // Default pakai gambar lama
                
                if (isset($_FILES['market_image']) && $_FILES['market_image']['error'] == 0) {
                    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                    $file_info = pathinfo($_FILES['market_image']['name']);
                    $extension = strtolower($file_info['extension']);
                    
                    if (in_array($extension, $allowed_extensions)) {
                        // Buat nama file unik agar tidak timpa
                        $new_filename = 'market_' . $market_id . '_' . time() . '.' . $extension;
                        $upload_dir = 'uploads/';
                        
                        // Buat folder uploads jika belum ada
                        if (!is_dir($upload_dir)) {
                            mkdir($upload_dir, 0777, true);
                        }
                        
                        $target_path = $upload_dir . $new_filename;
                        
                        if (move_uploaded_file($_FILES['market_image']['tmp_name'], $target_path)) {
                            $image_filename = $new_filename;
                            
                            // Hapus gambar lama jika ada (opsional)
                            if (!empty($existing_image) && file_exists($upload_dir . $existing_image)) {
                                unlink($upload_dir . $existing_image);
                            }
                        } else {
                            $error = 'Gagal mengupload gambar. Periksa izin folder.';
                        }
                    } else {
                        $error = 'Format gambar tidak didukung. Gunakan JPG, PNG, GIF, atau WEBP.';
                    }
                }
                // --- END LOGIKA UPLOAD GAMBAR ---

                // Jika tidak ada error upload, lanjutkan update database
                if (empty($error)) {
                    // Jika result_end_time kosong, set NULL (otomatis +1 jam dari result_time)
                    if (empty($result_end_time)) {
                        $result_end_time = null;
                    }

                    // Update market_name, display_name, result_time, result_end_time, dan image di database
                    $stmt = $db->prepare("UPDATE markets SET 
                        market_name = ?,
                        display_name = ?, 
                        result_time = ?, 
                        result_end_time = ?, 
                        image = ?,
                        updated_at = NOW()
                        WHERE id = ?");
                    
                    $stmt->execute([$market_name, $display_name, $result_time, $result_end_time, $image_filename, $market_id]);
                    
                    $_SESSION['success_message'] = 'Data market berhasil diupdate!';
                    header("Location: index.php");
                    exit();
                }
            }
        } catch (PDOException $e) {
            $error = 'Gagal mengupdate data: ' . $e->getMessage();
        }
    }
}

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

<!DOCTYPE html>
<html>
<head>
    <title>Edit Market - PAPUAPOOLS Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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>
        body { background-color: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .container { margin-top: 40px; }
        .card { border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); border: none; overflow: hidden; }
        .card-header { background: linear-gradient(45deg, #343a40, #2c3136); color: white; border-bottom: none; padding: 1.5rem; }
        .card-header h4 { margin: 0; }
        .card-body { padding: 2rem; }
        .market-info { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .market-info .label { font-weight: 600; color: #6c757d; }
        .current-display { font-size: 1.2rem; font-weight: 600; color: #007bff; }
        .btn-update { background: linear-gradient(45deg, #007bff, #0056b3); border: none; padding: 10px 30px; font-weight: 600; }
        .btn-update:hover { background: linear-gradient(45deg, #0056b3, #004085); transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,123,255,0.3); }
        .form-control { border-radius: 8px; border: 1px solid #ddd; padding: 12px 15px; }
        .img-preview { max-width: 200px; max-height: 200px; border-radius: 8px; border: 2px solid #ddd; padding: 5px; margin-top: 10px; }
    </style>
</head>
<body>
<?php include 'navbar.php'; ?>

<div class="container">
    <div class="row">
        <div class="col-lg-8 offset-lg-2">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4><i class="fas fa-edit mr-2"></i> Edit Market</h4>
                        <a href="index.php" class="btn btn-outline-light btn-sm">
                            <i class="fas fa-arrow-left"></i> Kembali ke Dashboard
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($error) ?>
                            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle mr-2"></i> <?= htmlspecialchars($_SESSION['success_message']) ?>
                            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <!-- Informasi Market -->
                    <div class="market-info">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="label">ID Market</div>
                                <div class="font-weight-bold">#<?= $market['id'] ?></div>
                            </div>
                            <div class="col-md-6">
                                <div class="label">Status Saat Ini</div>
                                <div><span class="badge badge-<?= $market['status'] == 1 ? 'success' : 'danger' ?> px-3 py-2"><?= $market['status'] == 1 ? 'Aktif' : 'Non-Aktif' ?></span></div>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-4">
                                <div class="label">Jam Tutup (Result Time)</div>
                                <div><span class="badge badge-danger px-3 py-2"><i class="fas fa-clock"></i> <?= substr($market['result_time'], 0, 5) ?></span></div>
                            </div>
                            <div class="col-md-4">
                                <div class="label">Jam Buka (Result End Time)</div>
                                <div>
                                    <?php if (!empty($market['result_end_time'])): ?>
                                        <span class="badge badge-success px-3 py-2"><i class="fas fa-check-circle"></i> <?= substr($market['result_end_time'], 0, 5) ?></span>
                                    <?php else: ?>
                                        <span class="text-muted"><i class="fas fa-info-circle"></i> Otomatis +1 jam</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="label">Dibuat</div>
                                <div><small class="text-muted"><?= date('d/m/Y H:i', strtotime($market['created_at'])) ?></small></div>
                            </div>
                        </div>
                    </div>

                    <!-- Form Edit -->
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                        
                        <!-- FIELD NAMA MARKET (BARU) -->
                        <div class="form-group">
                            <label for="market_name" class="font-weight-bold"><i class="fas fa-store mr-1"></i> 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>
                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Nama unik untuk identifikasi market di database.</small>
                        </div>

                        <div class="form-group">
                            <label for="display_name" class="font-weight-bold"><i class="fas fa-tag mr-1"></i> 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']) ?>" required>
                            <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Nama yang akan ditampilkan di website.</small>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="result_time" class="font-weight-bold text-danger"><i class="fas fa-lock mr-1"></i> Jam Tutup (Mulai Calculation)</label>
                                    <input type="time" class="form-control" id="result_time" name="result_time" 
                                           value="<?= isset($_POST['result_time']) ? htmlspecialchars($_POST['result_time']) : htmlspecialchars(substr($market['result_time'] ?? '15:30', 0, 5)) ?>" required>
                                    <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Pada jam ini, countdown berhenti & mulai CALCULATION.</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="result_end_time" class="font-weight-bold text-success"><i class="fas fa-unlock mr-1"></i> Jam Buka (Selesai Calculation)</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']) : htmlspecialchars(substr($market['result_end_time'] ?? '', 0, 5)) ?>">
                                    <small class="form-text text-muted"><i class="fas fa-info-circle"></i> Jika dikosongkan, sistem otomatis <strong>+1 jam</strong> dari Jam Tutup.</small>
                                </div>
                            </div>
                        </div>

                        <!-- FITUR UPLOAD GAMBAR -->
                        <div class="form-group">
                            <label for="market_image" class="font-weight-bold"><i class="fas fa-image mr-1"></i> Gambar Pasaran</label>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="market_image" name="market_image" accept="image/*">
                                <label class="custom-file-label" for="market_image">Pilih gambar...</label>
                            </div>
                            <small class="form-text text-muted">Format: JPG, PNG, GIF, WEBP. Maksimal 2MB.</small>
                            
                            <!-- Preview Gambar Lama -->
                            <?php if (!empty($market['image'])): ?>
                                <div class="mt-2">
                                    <p class="mb-1 text-muted small">Gambar Saat Ini:</p>
                                    <img src="uploads/<?= htmlspecialchars($market['image']) ?>" class="img-preview" alt="Gambar Market">
                                    <input type="hidden" name="existing_image" value="<?= htmlspecialchars($market['image']) ?>">
                                </div>
                            <?php else: ?>
                                <input type="hidden" name="existing_image" value="">
                                <div class="mt-2 text-muted small">Belum ada gambar untuk pasaran ini.</div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-group mb-0">
                            <button type="submit" class="btn btn-primary btn-update"><i class="fas fa-save mr-2"></i> Simpan Perubahan</button>
                            <a href="index.php" class="btn btn-secondary ml-2"><i class="fas fa-times mr-2"></i> Batal</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        // Auto dismiss alert
        setTimeout(function() { $('.alert').fadeOut('slow'); }, 5000);
        
        // Update label file input saat user memilih file
        $('.custom-file-input').on('change', function() {
            let fileName = $(this).val().split('\\').pop();
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        });
    });
</script>
</body>
</html>