<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'Unauthorized'])); }
require_once '../connect.php';

$account_id = $_SESSION['account_id'];
$user_id    = $_SESSION['user_id'];
$raw  = file_get_contents('php://input');
$json = $raw ? json_decode($raw, true) : null;
$action = $_POST['action'] ?? ($json['action'] ?? '');

switch ($action) {

    // ─────────────────────────────────────────────────────
    case 'add':
    case 'edit':
        requirePermission($conn, 'audience', ($_POST['audience_id'] ?? 0) ? 'edit' : 'add');
        $name          = sanitize($conn, $_POST['name'] ?? '');
        $description   = sanitize($conn, $_POST['description'] ?? '');
        $statuss       = (int)($_POST['statuss'] ?? 1);
        $audience_id   = (int)($_POST['audience_id'] ?? 0);
        $sel_customers = $_POST['selected_customers'] ?? [];

        if (!$name) jsonResponse(false, 'Audience name required');

        if ($audience_id) {
            $conn->query("UPDATE audience SET
                name='$name',
                description='$description',
                statuss=$statuss,
                date_updated=NOW()
                WHERE id=$audience_id AND (account_id=$account_id OR account_id IS NULL)");

            // Replace all customer associations
            $conn->query("DELETE FROM audience_customers WHERE audience_id=$audience_id");
            foreach ($sel_customers as $cid) {
                $cid = (int)$cid;
                if ($cid) $conn->query("INSERT INTO audience_customers (audience_id, customer_id) VALUES ($audience_id, $cid)");
            }
            jsonResponse(true, 'Audience updated');

        } else {
            $conn->query("INSERT INTO audience (name, description, statuss, account_id, added_by)
                          VALUES ('$name', '$description', $statuss, $account_id, $user_id)");
            $new_id = $conn->insert_id;

            foreach ($sel_customers as $cid) {
                $cid = (int)$cid;
                if ($cid) $conn->query("INSERT INTO audience_customers (audience_id, customer_id) VALUES ($new_id, $cid)");
            }
            jsonResponse(true, 'Audience created', ['id' => $new_id]);
        }
        break;

    // ─────────────────────────────────────────────────────
    case 'get':
        $id  = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $aud = $conn->query("SELECT * FROM audience WHERE id=$id AND (account_id=$account_id OR account_id IS NULL)")->fetch_assoc();
        if (!$aud) jsonResponse(false, 'Not found');

        $cur = $conn->query("SELECT customer_id FROM audience_customers WHERE audience_id=$id");
        $ids = [];
        while ($r = $cur->fetch_assoc()) $ids[] = $r['customer_id'];
        $aud['customer_ids'] = $ids;

        jsonResponse(true, '', ['data' => $aud]);
        break;

    // ─────────────────────────────────────────────────────
    case 'delete':
        requirePermission($conn, 'audience', 'delete');
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $conn->query("DELETE FROM audience WHERE id=$id AND (account_id=$account_id OR account_id IS NULL)");
        jsonResponse(true, 'Audience deleted');
        break;

    // ─────────────────────────────────────────────────────
    case 'toggle_status':
        requirePermission($conn, 'audience', 'edit');
        $id     = (int)($json['id']     ?? $_POST['id']     ?? 0);
        $status = (int)($json['status'] ?? $_POST['status'] ?? 0);
        $conn->query("UPDATE audience SET statuss=$status WHERE id=$id AND (account_id=$account_id OR account_id IS NULL)");
        jsonResponse(true, 'Status updated');
        break;

    // ─────────────────────────────────────────────────────
    // Get ALL customers in audience (used by View Members modal — no pagination needed there)
    case 'get_customers':
        $audience_id = (int)($json['audience_id'] ?? $_POST['audience_id'] ?? 0);
        if (!$audience_id) jsonResponse(false, 'Audience ID required');

        $res = $conn->query("
            SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
            FROM audience_customers ac
            LEFT JOIN customers c ON ac.customer_id = c.id
            WHERE ac.audience_id = $audience_id AND c.account_id = $account_id
            ORDER BY c.customer_name
        ");

        $list = [];
        while ($r = $res->fetch_assoc()) $list[] = $r;
        jsonResponse(true, '', ['customers' => $list]);
        break;

    // ─────────────────────────────────────────────────────
    // Paginated current members — for Manage Members modal
    case 'get_customers_paged':
        $audience_id = (int)($json['audience_id'] ?? $_POST['audience_id'] ?? 0);
        $offset      = (int)($json['offset']      ?? $_POST['offset']      ?? 0);
        $limit       = min((int)($json['limit']   ?? $_POST['limit']       ?? 12), 50);
        if (!$audience_id) jsonResponse(false, 'Audience ID required');

        $res = $conn->query("
            SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
            FROM audience_customers ac
            LEFT JOIN customers c ON ac.customer_id = c.id
            WHERE ac.audience_id = $audience_id AND c.account_id = $account_id
            ORDER BY c.customer_name
            LIMIT $limit OFFSET $offset
        ");

        $list = [];
        while ($r = $res->fetch_assoc()) $list[] = $r;
        jsonResponse(true, '', ['customers' => $list]);
        break;

    // ─────────────────────────────────────────────────────
    // Paginated customer search — for Add/Edit Audience modal (all customers)
    case 'search_customers_paged':
        $search = sanitize($conn, $json['search'] ?? $_POST['search'] ?? '');
        $offset = (int)($json['offset'] ?? $_POST['offset'] ?? 0);
        $limit  = min((int)($json['limit'] ?? $_POST['limit'] ?? 30), 100);

        $searchCond = '';
        if ($search) {
            $searchCond = "AND (c.customer_name LIKE '%$search%'
                            OR c.business_name LIKE '%$search%'
                            OR c.phone LIKE '%$search%'
                            OR c.email LIKE '%$search%')";
        }

        $res = $conn->query("
            SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
            FROM customers c
            WHERE c.account_id = $account_id
            $searchCond
            ORDER BY c.customer_name
            LIMIT $limit OFFSET $offset
        ");

        $list = [];
        while ($r = $res->fetch_assoc()) $list[] = $r;
        jsonResponse(true, '', ['customers' => $list]);
        break;

    // ─────────────────────────────────────────────────────
    // Paginated available-customer search (excludes current audience members) — Manage Members modal
    case 'search_customers_paged_excl':
        $search      = sanitize($conn, $json['search']      ?? $_POST['search']      ?? '');
        $audience_id = (int)($json['audience_id']            ?? $_POST['audience_id'] ?? 0);
        $offset      = (int)($json['offset']                 ?? $_POST['offset']      ?? 0);
        $limit       = min((int)($json['limit']              ?? $_POST['limit']       ?? 12), 50);

        $searchCond = '';
        if ($search) {
            $searchCond = "AND (c.customer_name LIKE '%$search%'
                            OR c.business_name LIKE '%$search%'
                            OR c.phone LIKE '%$search%'
                            OR c.email LIKE '%$search%')";
        }

        $exclusion = $audience_id
            ? "AND c.id NOT IN (SELECT customer_id FROM audience_customers WHERE audience_id = $audience_id)"
            : '';

        $res = $conn->query("
            SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
            FROM customers c
            WHERE c.account_id = $account_id
            $exclusion
            $searchCond
            ORDER BY c.customer_name
            LIMIT $limit OFFSET $offset
        ");

        $list = [];
        while ($r = $res->fetch_assoc()) $list[] = $r;
        jsonResponse(true, '', ['customers' => $list]);
        break;

    // ─────────────────────────────────────────────────────
    // Legacy search_customers — kept for backwards compat
    case 'search_customers':
        $search      = sanitize($conn, $json['search']      ?? $_POST['search']      ?? '');
        $audience_id = (int)($json['audience_id']            ?? $_POST['audience_id'] ?? 0);

        $searchCond = $search ? "AND (c.customer_name LIKE '%$search%'
             OR c.business_name LIKE '%$search%'
             OR c.phone LIKE '%$search%'
             OR c.email LIKE '%$search%')" : '';

        $res = $conn->query("
            SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
            FROM customers c
            WHERE c.account_id = $account_id
            AND c.id NOT IN (
                SELECT customer_id FROM audience_customers WHERE audience_id = $audience_id
            )
            $searchCond
            ORDER BY c.customer_name
            LIMIT 50
        ");

        $list = [];
        while ($r = $res->fetch_assoc()) $list[] = $r;
        jsonResponse(true, '', ['customers' => $list]);
        break;

    // ─────────────────────────────────────────────────────
    case 'add_customer':
        requirePermission($conn, 'audience', 'edit');
        $audience_id = (int)($json['audience_id'] ?? $_POST['audience_id'] ?? 0);
        $customer_id = (int)($json['customer_id'] ?? $_POST['customer_id'] ?? 0);
        if (!$audience_id || !$customer_id) jsonResponse(false, 'Missing parameters');

        $check = $conn->query("SELECT id FROM audience_customers WHERE audience_id=$audience_id AND customer_id=$customer_id");
        if ($check->num_rows > 0) jsonResponse(false, 'Customer already in this audience');

        $conn->query("INSERT INTO audience_customers (audience_id, customer_id) VALUES ($audience_id, $customer_id)");
        jsonResponse(true, 'Customer added to audience');
        break;

    // ─────────────────────────────────────────────────────
    case 'remove_customer':
        requirePermission($conn, 'audience', 'edit');
        $audience_id = (int)($json['audience_id'] ?? $_POST['audience_id'] ?? 0);
        $customer_id = (int)($json['customer_id'] ?? $_POST['customer_id'] ?? 0);
        if (!$audience_id || !$customer_id) jsonResponse(false, 'Missing parameters');

        $conn->query("DELETE FROM audience_customers WHERE audience_id=$audience_id AND customer_id=$customer_id");
        jsonResponse(true, 'Customer removed from audience');
        break;

    // ─────────────────────────────────────────────────────
    default:
        jsonResponse(false, 'Invalid action');
}
?>