<?php
// Simple API to get latest offer
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Database connection
$host = 'localhost';
$username = 'kongutourist_offers';
$password = 'Uq$yrK527t(d.@7[';
$database = 'kongutourist_offers';

try {
    $conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get latest ACTIVE offer only (end_date must be in the future)
    $stmt = $conn->prepare("
        SELECT * FROM offers 
        WHERE end_date >= NOW() 
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    $stmt->execute();
    
    $offer = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($offer) {
        // Only prepend domain if image_url is a relative path
        if (!str_starts_with($offer['image_url'], 'http')) {
            $offer['image_url'] = 'https://test.kalpavrukshaits.com/kongutourist/' . $offer['image_url'];
        }
        echo json_encode(['success' => true, 'offer' => $offer]);
    } else {
        echo json_encode(['success' => false, 'message' => 'No active offers found']);
    }
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>