<?php
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/cors.php';
require_once '../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    // Check if deals table exists
    $checkTable = $db->query("SHOW TABLES LIKE 'deals'");
    $tableExists = $checkTable->rowCount() > 0;
    
    if (!$tableExists) {
        echo json_encode([
            'success' => true,
            'deals' => [],
            'message' => 'Deals table does not exist yet. Please run setup_deals.php first.',
            'table_exists' => false
        ]);
        exit;
    }
    
    // Get deals count
    $countQuery = $db->query("SELECT COUNT(*) as count FROM deals");
    $count = $countQuery->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Get sample deals
    $query = "SELECT * FROM deals ORDER BY created_at DESC LIMIT 5";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $deals = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'deals' => $deals,
        'count' => $count,
        'table_exists' => true,
        'message' => 'Deals API is working'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
?>