<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');

// --- KIỂM TRA KẾT NỐI CSDL NGAY TỪ ĐẦU ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error', 
        'message' => 'Lỗi nghiêm trọng: Không thể kết nối đến cơ sở dữ liệu. Vui lòng kiểm tra file cấu hình (init.php).'
    ]);
    exit;
}

if (session_status() == PHP_SESSION_NONE) { session_start(); }

$action = $_REQUEST['action'] ?? '';
$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];
$user_id = $_SESSION['user_id'] ?? 0;

function execute_query($conn, $sql, $params = [], $types = "") {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        // Trả về lỗi nếu không thể prepare statement
        return false;
    }
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    return $result;
}

function get_customer_count_for_group($conn, $group_id) {
    if ($group_id <= 0) return 0;

    $conditions_result = execute_query($conn, "SELECT conditions FROM cms_customer_groups WHERE id = ?", [$group_id], 'i');
    if (!$conditions_result || $conditions_result->num_rows == 0) return 0;

    $conditions_json = $conditions_result->fetch_assoc()['conditions'] ?? '{}';
    $conditions = json_decode($conditions_json, true);

    if (empty($conditions)) return 0;
    
    $sql_count = "SELECT COUNT(DISTINCT c.ID) as total FROM cms_customers c ";
    $join_clause = "";
    $where_clauses = ["c.deleted = 0"];
    $count_params = [];
    $count_types = "";

    if (isset($conditions['min_total_purchase']) && is_numeric($conditions['min_total_purchase'])) {
        $join_clause = "JOIN (SELECT customer_id, SUM(total_money) as total_spent FROM cms_orders WHERE deleted = 0 AND order_status > 0 GROUP BY customer_id) as s ON c.ID = s.customer_id";
        $where_clauses[] = "s.total_spent >= ?";
        $count_params[] = $conditions['min_total_purchase'];
        $count_types .= "d";
    }
    if (isset($conditions['new_customer_days']) && is_numeric($conditions['new_customer_days'])) {
        $where_clauses[] = "c.created >= DATE_SUB(NOW(), INTERVAL ? DAY)";
        $count_params[] = $conditions['new_customer_days'];
        $count_types .= "i";
    }

    if (count($where_clauses) > 0) {
        $sql_count .= $join_clause . " WHERE " . implode(" AND ", $where_clauses);
        $count_result = execute_query($conn, $sql_count, $count_params, $count_types);
        return $count_result ? ($count_result->fetch_assoc()['total'] ?? 0) : 0;
    }
    return 0;
}

if ($action == 'search_templates') {
    $term = trim($_GET['term'] ?? '');
    $searchTerm = "%{$term}%";
    $result = execute_query($conn, "SELECT id, title as text, content FROM cms_message_templates WHERE title LIKE ?", [$searchTerm], 's');
    $response = ['status' => 'success', 'data' => $result ? $result->fetch_all(MYSQLI_ASSOC) : []];
}

if ($action == 'get_customer_groups') {
    $result = execute_query($conn, "SELECT id, group_name as text FROM cms_customer_groups");
    $response = ['status' => 'success', 'data' => $result ? $result->fetch_all(MYSQLI_ASSOC) : []];
}

if ($action == 'search_customers') {
    $term = trim($_GET['term'] ?? '');
    $searchTerm = "%{$term}%";
    $result = execute_query($conn, "SELECT ID as id, CONCAT(customer_name, ' - ', customer_phone) as text FROM cms_customers WHERE deleted = 0 AND (customer_name LIKE ? OR customer_phone LIKE ?) LIMIT 10", [$searchTerm, $searchTerm], 'ss');
    $response = ['status' => 'success', 'data' => $result ? $result->fetch_all(MYSQLI_ASSOC) : []];
}

if ($action == 'get_group_count') {
    $group_id = intval($_GET['group_id'] ?? 0);
    $count = get_customer_count_for_group($conn, $group_id);
    $response = ['status' => 'success', 'count' => $count];
}

if ($action == 'create_campaign') {
    $campaign_name = $_POST['campaign_name'] ?? 'Chiến dịch không tên';
    $message_content = $_POST['message_content'] ?? '';
    $recipient_type = $_POST['recipient_type'] ?? '';
    
    $recipient_details_text = "";
    $recipient_count = 0;

    if ($recipient_type == 'group') {
        $group_id = intval($_POST['recipient_group'] ?? 0);
        $group_result = execute_query($conn, "SELECT group_name FROM cms_customer_groups WHERE id = ?", [$group_id], 'i');
        $recipient_details_text = $group_result ? ($group_result->fetch_assoc()['group_name'] ?? 'Nhóm không xác định') : 'Nhóm không xác định';
        $recipient_count = get_customer_count_for_group($conn, $group_id);
    } else {
        $individual_ids = is_array($_POST['recipient_individuals']) ? $_POST['recipient_individuals'] : [];
        $recipient_count = count($individual_ids);
        $recipient_details_text = "{$recipient_count} người nhận cá nhân";
    }
    
    $stmt_campaign = $conn->prepare("INSERT INTO cms_message_campaigns (campaign_name, message_content, recipient_type, recipient_details, recipient_count, status, created_by) VALUES (?, ?, ?, ?, ?, 'completed', ?)");
    $stmt_campaign->bind_param('ssssii', $campaign_name, $message_content, $recipient_type, $recipient_details_text, $recipient_count, $user_id);
    
    if ($stmt_campaign->execute()) {
        $response = ['status' => 'success', 'message' => 'Đã tạo và gửi chiến dịch thành công (mô phỏng).'];
    } else {
        $response = ['status' => 'error', 'message' => 'Không thể tạo chiến dịch. Vui lòng thử lại.'];
    }
    $stmt_campaign->close();
}

if ($action == 'get_campaign_history') {
    $result = execute_query($conn, "SELECT campaign_name, message_content, recipient_details, recipient_count, created_at FROM cms_message_campaigns ORDER BY created_at DESC LIMIT 50");
    $response = ['status' => 'success', 'data' => $result ? $result->fetch_all(MYSQLI_ASSOC) : []];
}

echo json_encode($response);
?>