<?php
// Working version - handles form dates properly
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Create directories
        $dataDir = __DIR__ . '/../data';
        $imagesDir = __DIR__ . '/../images/offers';
        
        if (!file_exists($dataDir)) mkdir($dataDir, 0755, true);
        if (!file_exists($imagesDir)) mkdir($imagesDir, 0755, true);
        
        // Handle image upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
            $file = $_FILES['image'];
            $filename = 'offer_' . time() . '_' . $file['name'];
            $filepath = $imagesDir . '/' . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Get dates from form or use defaults
                $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';
                }
                
                // Create offer data
                $offer = [
                    'id' => uniqid(),
                    'title' => $_POST['title'] ?? '',
                    'image_url' => 'images/offers/' . $filename,
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                
                // Save to JSON file
                $offersFile = $dataDir . '/offers.json';
                $offers = [];
                
                if (file_exists($offersFile)) {
                    $existing = file_get_contents($offersFile);
                    if ($existing) $offers = json_decode($existing, true) ?: [];
                }
                
                $offers[] = $offer;
                file_put_contents($offersFile, json_encode($offers, JSON_PRETTY_PRINT));
                
                echo json_encode(['success' => true, 'message' => 'Offer saved successfully', 'offer' => $offer]);
                exit;
            }
        }
        
        echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
} else {
    // GET request - return current offer
    $offersFile = __DIR__ . '/../data/offers.json';
    if (file_exists($offersFile)) {
        $offers = json_decode(file_get_contents($offersFile), true) ?: [];
        if (!empty($offers)) {
            echo json_encode(['success' => true, 'offer' => end($offers)]);
            exit;
        }
    }
    echo json_encode(['success' => false, 'message' => 'No offers found']);
}
?>
