<?php
// Archivo para aprobar plantillas manualmente
require_once '../config/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db = Database::connect();
        $action = $_POST['action'] ?? '';
        
        if ($action === 'approve_all') {
            // Aprobar todas las plantillas pendientes
            $stmt = $db->prepare("UPDATE whatsapp_templates SET status = 'approved' WHERE status = 'pending'");
            $result = $stmt->execute();
            
            if ($result) {
                $affected = $stmt->rowCount();
                echo json_encode([
                    'success' => true, 
                    'message' => "Se aprobaron $affected plantillas exitosamente"
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Error al aprobar las plantillas']);
            }
        } 
        elseif ($action === 'approve_specific' && !empty($_POST['template_name'])) {
            // Aprobar plantilla específica
            $templateName = $_POST['template_name'];
            $stmt = $db->prepare("UPDATE whatsapp_templates SET status = 'approved' WHERE name = ?");
            $result = $stmt->execute([$templateName]);
            
            if ($result && $stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => true, 
                    'message' => "Plantilla '$templateName' aprobada exitosamente"
                ]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Plantilla no encontrada o ya aprobada']);
            }
        }
        else {
            echo json_encode(['success' => false, 'message' => 'Acción no válida']);
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
} 
elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Mostrar estado actual de plantillas
    try {
        $db = Database::connect();
        $stmt = $db->prepare("SELECT name, status, language, category FROM whatsapp_templates ORDER BY name");
        $stmt->execute();
        $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'templates' => $templates,
            'summary' => [
                'total' => count($templates),
                'approved' => count(array_filter($templates, fn($t) => $t['status'] === 'approved')),
                'pending' => count(array_filter($templates, fn($t) => $t['status'] === 'pending')),
                'rejected' => count(array_filter($templates, fn($t) => $t['status'] === 'rejected'))
            ]
        ]);
    } catch (Exception $e) {
        echo json_encode([
            'success' => false, 
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}
?>