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

$database = new Database();
$db = $database->getConnection();
$deal = new Deal($db);

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($deal);
            break;
        case 'POST':
            handlePostRequest($deal);
            break;
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

function handleGetRequest($deal)
{
    $id = $_GET['id'] ?? null;
    $userId = $_GET['user_id'] ?? null;
    
    if ($id) {
        $result = $deal->getDealById($id);
        if ($result) {
            // Add image URLs
            if (!empty($result['product_images'])) {
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                $host = $_SERVER['HTTP_HOST'];
                foreach ($result['product_images'] as &$image) {
                    $image = $protocol . $host . '/api/uploads/products/' . $image;
                }
            }
            
            // If user ID provided, get their progress
            if ($userId) {
                $progress = $deal->getUserDealProgress($userId, $id);
                $result['user_progress'] = $progress;
            }
            
            echo json_encode($result);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Deal not found']);
        }
    } else {
        $limit = $_GET['limit'] ?? 20;
        $deals = $deal->getActiveDeals($limit);
        
        // Add image URLs
        foreach ($deals as &$dealItem) {
            if ($dealItem['product_image']) {
                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
                $host = $_SERVER['HTTP_HOST'];
                $dealItem['product_image'] = $protocol . $host . '/api/uploads/products/' . $dealItem['product_image'];
            }
        }
        
        echo json_encode(['deals' => $deals]);
    }
}

function handlePostRequest($deal)
{
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!$data) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON data']);
        return;
    }
    
    $action = $data['action'] ?? '';
    
    switch ($action) {
        case 'verify_social':
            handleSocialVerification($deal, $data);
            break;
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Invalid action']);
            break;
    }
}

// deals/index.php
function handleSocialVerification($deal, $data)
{
    $userId = $data['user_id'] ?? null;
    $dealId = $data['deal_id'] ?? null;
    $platform = $data['platform'] ?? null;
    
    // 1. Basic check for required data
    if (!$userId || !$dealId || !$platform) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields.']);
        return;
    }
    
    // 2. Directly update the database to mark this step as complete
    $updateResult = $deal->updateUserProgress($userId, $dealId, $platform, true);
    
    if (!$updateResult) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update status in the database.']);
        return;
    }
    
    // 3. Get the complete, updated progress from the database
    $progress = $deal->getUserDealProgress($userId, $dealId);
    
    if ($progress) {
        // IMPORTANT: Ensure boolean values are sent as true/false, not 1/0
        $progress['has_followed_instagram'] = (bool) $progress['has_followed_instagram'];
        $progress['has_subscribed_youtube'] = (bool) $progress['has_subscribed_youtube'];
        $progress['deal_unlocked'] = (bool) $progress['deal_unlocked'];

        // 4. Send the successful response back to the frontend
        echo json_encode([
            'message' => ucfirst($platform) . ' verification completed!',
            'progress' => $progress
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Could not retrieve updated progress after update.']);
    }
}
?>