<?php
// Prevent any output before JSON
ob_start();

require_once __DIR__ . '/../db_config.php';
require_once __DIR__ . '/auth_rbac.php';

// Initialize auth and check permissions
$auth = new AdminAuth();
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Check if user has permission to manage products
if (!$auth->hasPermission('payments')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Clear any output buffer and set JSON header
ob_clean();
header('Content-Type: application/json');

// Get action from GET, POST, or JSON body
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// If no action found, try JSON input
if (!$action) {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
}

try {
    // Get database connection
    $conn = getDBConnection();
    
    switch ($action) {
        case 'get_tiers':
            $productId = intval($_GET['product_id']);
            
            if (!$productId) {
                echo json_encode(['success' => false, 'message' => 'Product ID required']);
                break;
            }
            
            // Get pricing tiers for the product
            $sql = "SELECT * FROM product_pricing WHERE product_id = ? ORDER BY pricing_tier ASC";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$productId]);
            $tiers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'tiers' => $tiers,
                'count' => count($tiers)
            ]);
            break;
            
        case 'save_pricing':
            // Get JSON input for save_pricing
            $input = json_decode(file_get_contents('php://input'), true);
            $productId = intval($input['product_id']);
            $basePrice = floatval($input['base_price']);
            $tiers = $input['tiers'] ?? [];
            
            if (!$productId) {
                echo json_encode(['success' => false, 'message' => 'Product ID required']);
                break;
            }
            
            $conn->beginTransaction();
            
            try {
                // Update base price
                $updateSql = "UPDATE products SET base_price = ?, updated_at = NOW() WHERE id = ?";
                $updateStmt = $conn->prepare($updateSql);
                $updateStmt->execute([$basePrice, $productId]);
                
                // Delete existing pricing tiers
                $deleteSql = "DELETE FROM product_pricing WHERE product_id = ?";
                $deleteStmt = $conn->prepare($deleteSql);
                $deleteStmt->execute([$productId]);
                
                // Insert new pricing tiers
                if (!empty($tiers)) {
                    $insertSql = "INSERT INTO product_pricing (product_id, pricing_tier, price, valid_from, valid_until, is_active, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())";
                    $insertStmt = $conn->prepare($insertSql);
                    
                    foreach ($tiers as $tier) {
                        $validFrom = !empty($tier['valid_from']) ? $tier['valid_from'] : null;
                        $validUntil = !empty($tier['valid_until']) ? $tier['valid_until'] : null;
                        
                        $insertStmt->execute([
                            $productId,
                            $tier['name'],
                            floatval($tier['price']),
                            $validFrom,
                            $validUntil
                        ]);
                    }
                }
                
                $conn->commit();
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Pricing tiers saved successfully'
                ]);
                
            } catch (Exception $e) {
                $conn->rollBack();
                throw $e;
            }
            break;
            
        case 'get_default_tier':
            $productId = intval($_GET['product_id']);
            
            if (!$productId) {
                echo json_encode(['success' => false, 'message' => 'Product ID required']);
                break;
            }
            
            // Get product base price first
            $productSql = "SELECT base_price FROM products WHERE id = ?";
            $productStmt = $conn->prepare($productSql);
            $productStmt->execute([$productId]);
            $product = $productStmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$product) {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
                break;
            }
            
            // Find the default tier (one with base price and no date restrictions)
            $sql = "SELECT pricing_tier FROM product_pricing 
                    WHERE product_id = ? AND price = ? AND valid_from IS NULL AND valid_until IS NULL 
                    ORDER BY created_at ASC LIMIT 1";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$productId, $product['base_price']]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'tier_name' => $result ? $result['pricing_tier'] : ''
            ]);
            break;
            
        case 'check_category_products':
            $input = json_decode(file_get_contents('php://input'), true);
            $categoryId = intval($input['category_id'] ?? 0);
            
            if (!$categoryId) {
                echo json_encode(['success' => false, 'message' => 'Category ID required']);
                break;
            }
            
            // Check how many products are assigned to this category
            $sql = "SELECT COUNT(*) as product_count FROM products WHERE category_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$categoryId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'product_count' => intval($result['product_count'])
            ]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
    
} catch (Exception $e) {
    if (isset($conn) && $conn->inTransaction()) {
        $conn->rollBack();
    }
    
    // Clear any output buffer before sending JSON
    ob_clean();
    header('Content-Type: application/json');
    
    error_log("Product Pricing API Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred: ' . $e->getMessage(),
        'error_details' => $e->getTraceAsString()
    ]);
}
?>
