<?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, $db);
            break;
        case 'PUT':
            handlePutRequest($deal, $db);
            break;
        case 'DELETE':
            handleDeleteRequest($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;
    
    if ($id) {
        try {
            $result = $deal->getDealByIdForAdmin($id);
            if ($result) {
                echo json_encode($result);
            } else {
                http_response_code(404);
                echo json_encode(['error' => 'Deal not found']);
            }
        } catch (Exception $e) {
            // If table doesn't exist or other error
            http_response_code(404);
            echo json_encode(['error' => 'Deal not found', 'debug' => $e->getMessage()]);
        }
    } else {
        try {
            // Check if deals table exists
            $checkTable = $deal->conn->query("SHOW TABLES LIKE 'deals'");
            if ($checkTable->rowCount() == 0) {
                // Table doesn't exist, return empty array with setup flag
                echo json_encode([
                    'deals' => [], 
                    'table_exists' => false,
                    'message' => 'Deals table not found. Please run database setup.'
                ]);
                return;
            }
            
            // Get all deals for admin (including inactive)
            $deals = $deal->getAllDealsForAdmin();
            
            // 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,
                'table_exists' => true,
                'count' => count($deals)
            ]);
        } catch (Exception $e) {
            // If there's any database error, return empty array with error info
            echo json_encode([
                'deals' => [], 
                'table_exists' => false,
                'error' => 'Database error: ' . $e->getMessage(),
                'message' => 'Please run database setup to create deals table.'
            ]);
        }
    }
}

function handlePostRequest($deal, $db)
{
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!$data) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON data']);
        return;
    }
    
    // Validate required fields
    $required = ['product_id', 'title', 'discount_percentage', 'original_price'];
    foreach ($required as $field) {
        if (!isset($data[$field]) || empty($data[$field])) {
            http_response_code(400);
            echo json_encode(['error' => "Missing required field: {$field}"]);
            return;
        }
    }
    
    // Calculate discounted price
    $discountedPrice = $data['original_price'] * (1 - ($data['discount_percentage'] / 100));
    
    // Set deal properties
    $deal->product_id = $data['product_id'];
    $deal->title = $data['title'];
    $deal->description = $data['description'] ?? '';
    $deal->discount_percentage = $data['discount_percentage'];
    $deal->original_price = $data['original_price'];
    $deal->discounted_price = $discountedPrice;
    $deal->is_flash_deal = $data['is_flash_deal'] ?? false;
    $deal->flash_deal_hours = $data['flash_deal_hours'] ?? 24;
    
    // Default social requirements
    $socialRequirements = $data['social_requirements'] ?? [
        'instagram' => [
            'handle' => '@mobileshop',
            'action' => 'follow',
            'required' => true
        ],
        'youtube' => [
            'handle' => '@mobileshop',
            'action' => 'subscribe',
            'required' => true
        ]
    ];
    
    $deal->social_requirements = json_encode($socialRequirements);
    
    $result = $deal->create();
    
    if ($result) {
        http_response_code(201);
        echo json_encode([
            'message' => 'Deal created successfully',
            'deal_id' => $result
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create deal']);
    }
}

function handlePutRequest($deal, $db)
{
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!$data || !isset($data['id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid data or missing deal ID']);
        return;
    }
    
    // Calculate discounted price if discount changed
    if (isset($data['discount_percentage']) && isset($data['original_price'])) {
        $data['discounted_price'] = $data['original_price'] * (1 - ($data['discount_percentage'] / 100));
    }
    
    // Set deal properties
    $deal->id = $data['id'];
    $deal->title = $data['title'] ?? '';
    $deal->description = $data['description'] ?? '';
    $deal->discount_percentage = $data['discount_percentage'] ?? 0;
    $deal->original_price = $data['original_price'] ?? 0;
    $deal->discounted_price = $data['discounted_price'] ?? 0;
    $deal->is_flash_deal = $data['is_flash_deal'] ?? false;
    $deal->flash_deal_hours = $data['flash_deal_hours'] ?? 24;
    $deal->is_active = $data['is_active'] ?? true;
    
    if (isset($data['social_requirements'])) {
        $deal->social_requirements = json_encode($data['social_requirements']);
    }
    
    $result = $deal->update();
    
    if ($result) {
        echo json_encode(['message' => 'Deal updated successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update deal']);
    }
}

function handleDeleteRequest($deal)
{
    $id = $_GET['id'] ?? null;
    
    if (!$id) {
        http_response_code(400);
        echo json_encode(['error' => 'Deal ID is required']);
        return;
    }
    
    $deal->id = $id;
    $result = $deal->delete();
    
    if ($result) {
        echo json_encode(['message' => 'Deal deleted successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to delete deal']);
    }
}
?>