<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'templates' => [],
    'users' => [],
    'channels' => [],
    'logs' => [],
    'total_pages' => 1,
    'page' => 1
];

if (!isLoggedIn() || getCurrentUser()['role'] !== 'admin') {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();
$tab = $_GET['tab'] ?? 'templates';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

try {
    $response['templates'] = $pdo->query("SELECT * FROM notification_templates ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['users'] = $pdo->query("SELECT id, username FROM users ORDER BY username ASC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['channels'] = $pdo->query("SELECT channel_name, is_enabled FROM notification_channels")->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['success'] = true;
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['success'] = false;
        $response['message'] = "Security check failed (CSRF).";
        echo json_encode($response);
        exit();
    }

    if (isset($_POST['save_template'])) {
        $template_id = (int)$_POST['template_id'];
        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');
        
        $channels_selected = $_POST['channels'] ?? [];
        if (!is_array($channels_selected)) {
            $channels_selected = $channels_selected ? explode(',', $channels_selected) : [];
        }
        $allowed_channels = ['in_app', 'email', 'sms', 'whatsapp'];
        $channels_selected = array_intersect($channels_selected, $allowed_channels);
        $channels_csv = implode(',', $channels_selected);

        if (empty($body)) {
            $response['message'] = "Template body cannot be empty.";
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE notification_templates SET subject = ?, body = ?, channels_csv = ? WHERE id = ?");
                $stmt->execute([$subject, $body, $channels_csv, $template_id]);
                $response['success'] = true;
                $response['message'] = "Template updated.";
            } catch (PDOException $e) {
                error_log("Template update error: " . $e->getMessage());
                $response['message'] = "Failed to update template. Please try again.";
            }
        }
    } elseif (isset($_POST['create_template'])) {
        $template_name = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($_POST['template_name'] ?? '')));
        $subject = trim($_POST['subject'] ?? '');
        $body = trim($_POST['body'] ?? '');
        
        $channels_selected = $_POST['channels'] ?? [];
        if (!is_array($channels_selected)) {
            $channels_selected = $channels_selected ? explode(',', $channels_selected) : [];
        }
        $allowed_channels = ['in_app', 'email', 'sms', 'whatsapp'];
        $channels_selected = array_intersect($channels_selected, $allowed_channels);
        $channels_csv = implode(',', $channels_selected);

        if (empty($template_name) || empty($body)) {
            $response['message'] = "Template key/name and body cannot be empty.";
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO notification_templates (template_name, subject, body, channels_csv) VALUES (?, ?, ?, ?)");
                $stmt->execute([$template_name, $subject, $body, $channels_csv]);
                $response['success'] = true;
                $response['message'] = "Custom template '$template_name' created successfully.";
            } catch (PDOException $e) {
                error_log("Template creation error: " . $e->getMessage());
                $response['message'] = "Failed to create template: Key name must be unique.";
            }
        }
    } elseif (isset($_POST['delete_template'])) {
        $template_id = (int)$_POST['template_id'];
        
        try {
            $stmt = $pdo->prepare("SELECT template_name FROM notification_templates WHERE id = ?");
            $stmt->execute([$template_id]);
            $temp_name = $stmt->fetchColumn();
            
            $core_templates = ['event_registration', 'kyc_status', 'payout_status', 'event_reminder', 'password_reset'];
            if (!$temp_name) {
                $response['message'] = "Template not found.";
            } elseif (in_array($temp_name, $core_templates)) {
                $response['message'] = "Core system templates cannot be deleted.";
            } else {
                $del = $pdo->prepare("DELETE FROM notification_templates WHERE id = ?");
                $del->execute([$template_id]);
                $response['success'] = true;
                $response['message'] = "Template deleted successfully.";
            }
        } catch (PDOException $e) {
            $response['message'] = "Failed to delete template: " . $e->getMessage();
        }
    } elseif (isset($_POST['send_broadcast'])) {
        $user_target = $_POST['user_target'] ?? 'all';
        $broadcast_type = $_POST['broadcast_type'] ?? 'manual';
        
        try {
            // Extend execution time limit for potentially large loops
            @set_time_limit(0);
            require_once __DIR__ . '/../../includes/notification_helper.php';
            
            $target_users = [];
            if ($user_target === 'all') {
                // Only send to active users to avoid spamming deleted/deactivated accounts
                $target_users = $pdo->query("SELECT id FROM users WHERE status = 'active'")->fetchAll(PDO::FETCH_COLUMN) ?: [];
            } else {
                $target_users[] = (int)$user_target;
            }

            $sent_count = 0;
            $total_users = count($target_users);
            
            if ($broadcast_type === 'template') {
                $template_name = trim($_POST['template_name'] ?? '');
                
                $placeholders = [
                    'event_title' => trim($_POST['event_title'] ?? 'Annual Conference'),
                    'location' => trim($_POST['location'] ?? 'Virtual'),
                    'start_date' => trim($_POST['start_date'] ?? date('Y-m-d H:i')),
                    'status' => trim($_POST['status'] ?? 'Active'),
                    'amount' => trim($_POST['amount'] ?? '0.00')
                ];
                
                foreach ($target_users as $idx => $uid) {
                    if (sendMultichannelNotification($uid, $template_name, $placeholders)) {
                        $sent_count++;
                    }
                    // Throttle to prevent channel flood
                    if ($total_users > 5) {
                        usleep(50000); // 50ms delay
                    }
                }
                
                $response['success'] = true;
                $response['message'] = "Template alerts successfully sent to $sent_count users.";
            } else {
                $title = trim($_POST['title'] ?? '');
                $message = trim($_POST['message'] ?? '');
                $channels_selected = $_POST['channels'] ?? [];
                if (!is_array($channels_selected)) {
                    $channels_selected = $channels_selected ? explode(',', $channels_selected) : [];
                }

                if (empty($title) || empty($message) || empty($channels_selected)) {
                    $response['message'] = "Title, message, and at least one channel are required.";
                } else {
                    foreach ($target_users as $idx => $uid) {
                        sendBroadcastNotification($uid, $title, $message, $channels_selected);
                        $sent_count++;
                        // Throttle to prevent channel flood
                        if ($total_users > 5) {
                            usleep(50000); // 50ms delay
                        }
                    }
                    $response['success'] = true;
                    $response['message'] = "Broadcast successfully dispatched to $sent_count users.";
                }
            }
        } catch (Exception $e) {
            error_log("Broadcast error: " . $e->getMessage());
            $response['message'] = "Failed to dispatch broadcast. Please try again.";
        }
    }
} else {
    // GET requests return logs
    if ($tab === 'logs') {
        try {
            $count = (int)$pdo->query("SELECT COUNT(*) FROM notifications")->fetchColumn();
            
            $stmt_d = $pdo->prepare("
                SELECT n.*, u.username 
                FROM notifications n 
                LEFT JOIN users u ON n.user_id = u.id 
                ORDER BY n.id DESC LIMIT ? OFFSET ?
            ");
            $stmt_d->bindValue(1, $limit, PDO::PARAM_INT);
            $stmt_d->bindValue(2, $offset, PDO::PARAM_INT);
            $stmt_d->execute();
            
            $response['logs'] = $stmt_d->fetchAll(PDO::FETCH_ASSOC) ?: [];
            $response['total_pages'] = max(1, ceil($count / $limit));
            $response['page'] = $page;
            $response['success'] = true;
        } catch (PDOException $e) { }
    }
}

echo json_encode($response);
