<?php
/**
 * API de Favoritos - MontaLoja
 * Gerencia favoritos do cliente (sync com banco de dados)
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Carregar configurações - ajuste o caminho conforme necessário
$configPath = __DIR__ . '/temp_config.php';
if (!file_exists($configPath)) {
    $configPath = __DIR__ . '/../includes/config.php';
}
if (!file_exists($configPath)) {
    $configPath = __DIR__ . '/../../../includes/config.php';
}
if (file_exists($configPath)) {
    require_once $configPath;
} else {
    echo json_encode(['success' => false, 'error' => 'Configuration file not found', 'debug' => __DIR__]);
    exit;
}

// Conexão com banco
try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
    exit;
}

// Iniciar sessão
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME ?? 'montaloja_session');
    session_start();
}

// Verificar se cliente está logado
$customerId = $_SESSION['customer_id'] ?? null;
$storeId = $_GET['store_id'] ?? $_POST['store_id'] ?? null;

if (!$storeId) {
    echo json_encode(['success' => false, 'error' => 'Store ID required']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// GET - Debug - Verificar status da sessão e conexão
if ($method === 'GET' && $action === 'debug') {
    $debug = [
        'success' => true,
        'session_id' => session_id(),
        'customer_id' => $customerId,
        'customer_name' => $_SESSION['customer_name'] ?? null,
        'customer_email' => $_SESSION['customer_email'] ?? null,
        'store_id_session' => $_SESSION['store_id'] ?? null,
        'store_id_request' => $storeId,
        'is_logged_in' => $customerId !== null,
        'config_loaded' => defined('DB_HOST'),
        'db_connected' => true,
        'table_exists' => false
    ];
    
    // Verificar se tabela existe
    try {
        $stmt = $pdo->query("SHOW TABLES LIKE 'customer_favorites'");
        $debug['table_exists'] = $stmt->rowCount() > 0;
        
        if ($debug['table_exists'] && $customerId) {
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM customer_favorites WHERE customer_id = ? AND store_id = ?");
            $stmt->execute([$customerId, $storeId]);
            $debug['favorites_count'] = $stmt->fetch()['count'];
        }
    } catch (Exception $e) {
        $debug['table_error'] = $e->getMessage();
    }
    
    echo json_encode($debug, JSON_PRETTY_PRINT);
    exit;
}

// GET - Listar favoritos do cliente
if ($method === 'GET' && $action === 'list') {
    if (!$customerId) {
        echo json_encode(['success' => true, 'favorites' => [], 'logged_in' => false]);
        exit;
    }
    
    $stmt = $pdo->prepare("
        SELECT cf.product_id, cf.created_at, p.name, p.price, p.image_url, p.id as product_id_check
        FROM customer_favorites cf
        JOIN products p ON p.id = cf.product_id
        WHERE cf.customer_id = ? AND cf.store_id = ?
        ORDER BY cf.created_at DESC
    ");
    $stmt->execute([$customerId, $storeId]);
    $favorites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Formatar dados
    $formatted = array_map(function($fav) {
        return [
            'id' => $fav['product_id'],
            'name' => $fav['name'],
            'price' => floatval($fav['price']),
            'image' => $fav['image_url'],
            'slug' => $fav['product_id'], // usando ID como fallback
            'addedAt' => $fav['created_at']
        ];
    }, $favorites);
    
    echo json_encode(['success' => true, 'favorites' => $formatted, 'logged_in' => true]);
    exit;
}

// POST - Adicionar favorito
if ($method === 'POST' && $action === 'add') {
    $productId = $_POST['product_id'] ?? null;
    
    if (!$productId) {
        echo json_encode(['success' => false, 'error' => 'Product ID required']);
        exit;
    }
    
    if (!$customerId) {
        echo json_encode(['success' => true, 'saved_to_db' => false, 'message' => 'Saved locally only']);
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("INSERT IGNORE INTO customer_favorites (customer_id, product_id, store_id) VALUES (?, ?, ?)");
        $stmt->execute([$customerId, $productId, $storeId]);
        echo json_encode(['success' => true, 'saved_to_db' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Failed to save']);
    }
    exit;
}

// POST - Remover favorito
if ($method === 'POST' && $action === 'remove') {
    $productId = $_POST['product_id'] ?? null;
    
    if (!$productId) {
        echo json_encode(['success' => false, 'error' => 'Product ID required']);
        exit;
    }
    
    if (!$customerId) {
        echo json_encode(['success' => true, 'removed_from_db' => false]);
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM customer_favorites WHERE customer_id = ? AND product_id = ? AND store_id = ?");
        $stmt->execute([$customerId, $productId, $storeId]);
        echo json_encode(['success' => true, 'removed_from_db' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Failed to remove']);
    }
    exit;
}

// POST - Sincronizar favoritos locais com banco
if ($method === 'POST' && $action === 'sync') {
    $localFavorites = json_decode($_POST['favorites'] ?? '[]', true);
    
    if (!$customerId) {
        echo json_encode(['success' => true, 'synced' => false, 'message' => 'Not logged in']);
        exit;
    }
    
    if (empty($localFavorites)) {
        echo json_encode(['success' => true, 'synced' => true, 'count' => 0]);
        exit;
    }
    
    try {
        $synced = 0;
        foreach ($localFavorites as $fav) {
            $productId = $fav['id'] ?? null;
            if ($productId) {
                $stmt = $pdo->prepare("INSERT IGNORE INTO customer_favorites (customer_id, product_id, store_id) VALUES (?, ?, ?)");
                $stmt->execute([$customerId, $productId, $storeId]);
                if ($stmt->rowCount() > 0) $synced++;
            }
        }
        echo json_encode(['success' => true, 'synced' => true, 'count' => $synced]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Sync failed']);
    }
    exit;
}

// POST - Limpar todos os favoritos
if ($method === 'POST' && $action === 'clear') {
    if (!$customerId) {
        echo json_encode(['success' => true, 'cleared_from_db' => false]);
        exit;
    }
    
    try {
        $stmt = $pdo->prepare("DELETE FROM customer_favorites WHERE customer_id = ? AND store_id = ?");
        $stmt->execute([$customerId, $storeId]);
        echo json_encode(['success' => true, 'cleared_from_db' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'Failed to clear']);
    }
    exit;
}

echo json_encode(['success' => false, 'error' => 'Invalid action']);
