<?php
ini_set('display_errors', 0);
header('Content-Type: application/json');
require 'db_connect.php';

$input = json_decode(file_get_contents("php://input"));
if (!$input) {
    echo json_encode(["success" => false, "msg" => "no_data"]);
    exit;
}

$action = $input->action ?? '';

// 1. GUARDAR PROYECTO
if ($action === 'save') {
    $uid = $conn->real_escape_string($input->user_id);
    $author = $conn->real_escape_string($input->author_name);
    $title = $conn->real_escape_string($input->title);
    $img = $conn->real_escape_string($input->image);
    $vis = $conn->real_escape_string($input->visibility);
    $cat = $conn->real_escape_string($input->category ?? 'Otros');

    $sql = "INSERT INTO projects (user_id, author_name, title, image_data, visibility, category) 
            VALUES ('$uid', '$author', '$title', '$img', '$vis', '$cat')";

    if ($conn->query($sql)) {
        // LÓGICA DE XP: Si el molde es público, premiamos al autor con 50 XP
        if ($vis === 'public') {
            $conn->query("UPDATE users SET xp = xp + 50 WHERE google_id = '$uid'");
        }
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "msg" => $conn->error]);
    }
}

// 2. LISTAR PROYECTOS (OPTIMIZADO)
if ($action === 'list') {
    $uid = $conn->real_escape_string($input->user_id);
    $type = $input->type; 
    $cat_filter = isset($input->category) ? $conn->real_escape_string($input->category) : 'Todas';
    $search = isset($input->search) ? $conn->real_escape_string($input->search) : '';
    $offset = isset($input->offset) ? (int)$input->offset : 0;
    $limit = 12;

    if ($type === 'private') {
        $where = "p.user_id = '$uid'";
    } else {
        $where = "p.visibility = 'public'";
    }

    if ($cat_filter !== 'Todas') $where .= " AND p.category = '$cat_filter'";
    if ($search !== '') $where .= " AND p.title LIKE '%$search%'";

    if ($type === 'favorites') {
        $sql = "SELECT p.*, u.fb_url, u.ig_url, u.tt_url,
                (SELECT COUNT(*) FROM likes WHERE project_id = p.id) as likes_total,
                (SELECT COUNT(*) FROM likes WHERE project_id = p.id AND user_id = '$uid') as user_liked
                FROM projects p
                INNER JOIN likes l ON p.id = l.project_id
                LEFT JOIN users u ON p.user_id = u.google_id
                WHERE l.user_id = '$uid' " . 
                ($cat_filter !== 'Todas' ? " AND p.category = '$cat_filter'" : "") . 
                ($search !== '' ? " AND p.title LIKE '%$search%'" : "") . "
                ORDER BY l.created_at DESC 
                LIMIT $offset, $limit";
    } else {
        $sql = "SELECT p.*, u.fb_url, u.ig_url, u.tt_url,
                (SELECT COUNT(*) FROM likes WHERE project_id = p.id) as likes_total,
                (SELECT COUNT(*) FROM likes WHERE project_id = p.id AND user_id = '$uid') as user_liked
                FROM projects p 
                LEFT JOIN users u ON p.user_id = u.google_id 
                WHERE $where 
                ORDER BY p.id DESC 
                LIMIT $offset, $limit";
    }
    
    $result = $conn->query($sql);
    $projects = [];
    if ($result) {
        while($row = $result->fetch_assoc()) {
            $projects[] = $row;
        }
    }
    $hasMore = (count($projects) === $limit);
    echo json_encode(["success" => true, "projects" => $projects, "hasMore" => $hasMore]);
}

// 3. COMPRAR (DESCARGAR) - LÓGICA DE CRÉDITOS Y XP
if ($action === 'buy') {
    $buyer_id = $conn->real_escape_string($input->buyer_id);
    $project_id = (int)$input->project_id; 

    $sql_proj = "SELECT user_id FROM projects WHERE id = $project_id LIMIT 1";
    $result_proj = $conn->query($sql_proj);

    if ($result_proj && $row_proj = $result_proj->fetch_assoc()) {
        $creator_id = $row_proj['user_id'];

        if ($buyer_id === $creator_id) {
            echo json_encode(["success" => true, "msg" => "autodescarga"]);
            exit;
        }

        $sql_check = "SELECT credits FROM users WHERE google_id = '$buyer_id'";
        $check = $conn->query($sql_check);
        $row = $check->fetch_assoc();

        if ($row && $row['credits'] > 0) {
            $update1 = "UPDATE users SET credits = credits - 1 WHERE google_id = '$buyer_id'";
            $update2 = "UPDATE users SET credits = credits + 1 WHERE google_id = '$creator_id'";
            
            if ($conn->query($update1) && $conn->query($update2)) {
                // LÓGICA DE XP: Premiamos al creador con 100 XP por vender un molde
                $conn->query("UPDATE users SET xp = xp + 100 WHERE google_id = '$creator_id'");
                
                echo json_encode(["success" => true, "new_credits" => $row['credits'] - 1]);
            } else {
                echo json_encode(["success" => false, "msg" => "error_sql_update"]);
            }
        } else {
            echo json_encode(["success" => false, "msg" => "sin_saldo"]);
        }
    } else {
        echo json_encode(["success" => false, "msg" => "proyecto_no_encontrado"]);
    }
}

// 4. ELIMINAR DISEÑOS (MODO ADMIN ACTUALIZADO PARA BORRADO MÚLTIPLE)
if ($action === 'delete_admin') {
    $admin_id_request = isset($input->admin_id) ? trim($input->admin_id) : '';
    
    // 👑 PON AQUÍ TU ID DE ADMINISTRADOR
    $admin_id_master = "115195460837221753009"; 
    
    // Verificamos que el ID que envía la petición sea exactamente igual al tuyo
    if ($admin_id_request === $admin_id_master) {
        
        // Verificamos si es un borrado por lotes (array) o uno individual
        if (isset($input->project_ids) && is_array($input->project_ids)) {
            // BORRADO POR LOTES
            $ids = array_map('intval', $input->project_ids);
            $ids_string = implode(',', $ids);
            $sql = "DELETE FROM projects WHERE id IN ($ids_string)";
        } else {
            // BORRADO INDIVIDUAL (Por si usas el botón individual en la tarjeta)
            $project_id = (int)$input->project_id;
            $sql = "DELETE FROM projects WHERE id = $project_id";
        }
        
        if ($conn->query($sql)) {
            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "msg" => "Error al eliminar de la base de datos"]);
        }
    } else {
        echo json_encode(["success" => false, "msg" => "No tienes permisos de administrador"]);
    }
    exit;
}

$conn->close();
?>