<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once __DIR__ . '/../config/config.php';

try {
    // Debug mode
    $debugMode = isset($_GET['debug']) || php_sapi_name() === 'cli';
    if (!$debugMode) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        if (!isset($_SESSION['user_id'])) {
            http_response_code(401);
            echo json_encode(['error' => 'No autorizado']);
            exit;
        }
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Método no permitido']);
        exit;
    }

    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(['error' => 'JSON inválido']);
        exit;
    }

    $db = Database::getInstance();
    
    $action = $input['action'] ?? '';
    
    switch ($action) {
        case 'update_status':
            $templateId = intval($input['template_id'] ?? 0);
            $newStatus = $input['status'] ?? '';
            
            if (!$templateId || !in_array($newStatus, ['pending', 'approved', 'rejected'])) {
                http_response_code(400);
                echo json_encode(['error' => 'template_id y status válido requeridos']);
                exit;
            }
            
            $stmt = $db->query(
                "UPDATE message_templates SET status = ?, updated_at = NOW() WHERE id = ?",
                [$newStatus, $templateId]
            );
            
            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Estado de plantilla actualizado correctamente',
                    'template_id' => $templateId,
                    'new_status' => $newStatus
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'error' => 'Plantilla no encontrada o no se pudo actualizar'
                ]);
            }
            break;
            
        case 'bulk_approve':
            $templateIds = $input['template_ids'] ?? [];
            
            if (empty($templateIds) || !is_array($templateIds)) {
                http_response_code(400);
                echo json_encode(['error' => 'template_ids requerido como array']);
                exit;
            }
            
            $placeholders = str_repeat('?,', count($templateIds) - 1) . '?';
            $stmt = $db->query(
                "UPDATE message_templates SET status = 'approved', updated_at = NOW() WHERE id IN ($placeholders)",
                $templateIds
            );
            
            echo json_encode([
                'success' => true,
                'message' => 'Plantillas aprobadas masivamente',
                'updated_count' => $stmt->rowCount()
            ]);
            break;
            
        case 'sync_from_meta':
            // Función futura para sincronizar desde Meta API
            echo json_encode([
                'success' => false,
                'error' => 'Función no implementada aún',
                'note' => 'Para implementar: consultar API de Meta para estado real de plantillas'
            ]);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Acción no válida']);
            break;
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno: ' . $e->getMessage()
    ]);
}
?>