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

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => 'Database connection failed']));
}

// Set headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Create directories if they don't exist
        $imagesDir = __DIR__ . '/../images/offers';
        if (!file_exists($imagesDir)) {
            mkdir($imagesDir, 0755, true);
        }
        
        // Handle image upload
        $imageUrl = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['image'];
            
            // Validate file type
            $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array($file['type'], $allowedTypes)) {
                echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed']);
                exit;
            }
            
            // Generate unique filename
            $filename = 'offer_' . time() . '_' . uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
            $filepath = $imagesDir . '/' . $filename;
            
            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                $imageUrl = 'images/offers/' . $filename;
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
                exit;
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Image upload failed']);
            exit;
        }
        
        // Get form data
        $title = $_POST['title'] ?? '';
        $startDate = $_POST['start_date'] ?? date('Y-m-d H:i:s');
        $endDate = $_POST['end_date'] ?? date('Y-m-d H:i:s', strtotime('+1 day'));
        
        // Convert datetime-local format to MySQL format
        if (preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $startDate)) {
            $startDate = str_replace('T', ' ', $startDate) . ':00';
        }
        if (preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $endDate)) {
            $endDate = str_replace('T', ' ', $endDate) . ':00';
        }
        
        // Insert offer into database
        $sql = "INSERT INTO offers (title, image_url, start_date, end_date) VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssss", $title, $imageUrl, $startDate, $endDate);
        
        if ($stmt->execute()) {
            $offerId = $conn->insert_id;
            echo json_encode([
                'success' => true, 
                'message' => 'Offer saved successfully',
                'offer' => [
                    'id' => $offerId,
                    'title' => $title,
                    'image_url' => $imageUrl,
                    'start_date' => $startDate,
                    'end_date' => $endDate
                ]
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to save offer: ' . $stmt->error]);
        }
        
        $stmt->close();
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get current active offer
    $now = date('Y-m-d H:i:s');
    $sql = "SELECT * FROM offers WHERE start_date <= ? AND end_date >= ? ORDER BY created_at DESC LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $now, $now);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $offer = $result->fetch_assoc();
        echo json_encode(['success' => true, 'offer' => $offer]);
    } else {
        echo json_encode(['success' => false, 'message' => 'No active offers found']);
    }
    
    $stmt->close();
}

$conn->close();
?>
