<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include config dari folder yang sama
require_once 'config.php';

// Cek login
checkLogin();

// Enable error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

if ($market_id > 0) {
    try {
        // Cek apakah market ada
        $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();
        }
        
        $market_name = $market['market_name'];
        
        // Mulai transaksi
        $db->beginTransaction();
        
        // 1. Hapus semua data result yang terkait
        $stmt = $db->prepare("DELETE FROM lottery_results WHERE market_id = ?");
        $stmt->execute([$market_id]);
        $deleted_results = $stmt->rowCount();
        
        // 2. Hapus market
        $stmt = $db->prepare("DELETE FROM markets WHERE id = ?");
        $stmt->execute([$market_id]);
        $deleted_market = $stmt->rowCount();
        
        // Commit transaksi
        $db->commit();
        
        if ($deleted_market > 0) {
            // Catat aktivitas admin
            if (function_exists('logAdminActivity')) {
                logAdminActivity('delete_market', 'Menghapus market: ' . $market_name . ' (ID: ' . $market_id . ') dengan ' . $deleted_results . ' data result');
            }
            
            $_SESSION['success_message'] = 'Market "' . htmlspecialchars($market_name) . '" berhasil dihapus! (' . $deleted_results . ' data result terhapus)';
        } else {
            $_SESSION['error_message'] = 'Gagal menghapus market!';
        }
        
    } catch (PDOException $e) {
        // Rollback jika error
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $_SESSION['error_message'] = 'Gagal menghapus market: ' . $e->getMessage();
    }
} else {
    $_SESSION['error_message'] = 'ID Market tidak valid!';
}

header("Location: add_result.php");
exit();
?>