<?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, 'campaigns', ($_POST['campaign_id'] ?? 0) ? 'edit' : 'add');
        $name = sanitize($conn, $_POST['name'] ?? '');
        $description = sanitize($conn, $_POST['description'] ?? '');
        $message_type_id = (int)($_POST['message_type_id'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);
        $audience_ids = $_POST['audience_ids'] ?? [];
        $campaign_id = (int)($_POST['campaign_id'] ?? 0);
        
        if (!$name) jsonResponse(false, 'Campaign name required');
        if (!$message_type_id) jsonResponse(false, 'Campaign type required');
        
        if ($campaign_id) {
            // Update existing
            $conn->query("UPDATE campaign SET 
                name='$name', 
                description='$description', 
                message_type_id=$message_type_id, 
                status=$status,
                date_updated=NOW()
                WHERE id=$campaign_id AND account_id=$account_id");
            
            // Update audiences (delete old, add new)
            $conn->query("DELETE FROM campaign_audience WHERE campaign_id=$campaign_id");
            foreach ($audience_ids as $aid) {
                $aid = (int)$aid;
                if ($aid) $conn->query("INSERT INTO campaign_audience (campaign_id, audience_id) VALUES ($campaign_id, $aid)");
            }
            jsonResponse(true, 'Campaign updated');
        } else {
            // Insert new
            $conn->query("INSERT INTO campaign (name, description, message_type_id, status, account_id, added_by) 
                          VALUES ('$name', '$description', $message_type_id, $status, $account_id, $user_id)");
            $new_id = $conn->insert_id;
            foreach ($audience_ids as $aid) {
                $aid = (int)$aid;
                if ($aid) $conn->query("INSERT INTO campaign_audience (campaign_id, audience_id) VALUES ($new_id, $aid)");
            }
            jsonResponse(true, 'Campaign created', ['id' => $new_id]);
        }
        break;
        
    case 'get':
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $camp = $conn->query("SELECT * FROM campaign WHERE id=$id AND account_id=$account_id")->fetch_assoc();
        if (!$camp) jsonResponse(false, 'Not found');
        
        $audiences = $conn->query("SELECT audience_id FROM campaign_audience WHERE campaign_id=$id");
        $audience_ids = [];
        while($row = $audiences->fetch_assoc()) $audience_ids[] = $row['audience_id'];
        $camp['audience_ids'] = $audience_ids;
        
        jsonResponse(true, '', ['data' => $camp]);
        break;
        
    case 'get_full':
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $camp = $conn->query("
            SELECT c.*, ct.name as type_name, u.name as creator_name 
            FROM campaign c
            LEFT JOIN message_type ct ON c.message_type_id = ct.id
            LEFT JOIN users u ON c.added_by = u.id
            WHERE c.id=$id AND c.account_id=$account_id
        ")->fetch_assoc();
        if (!$camp) jsonResponse(false, 'Not found');
        
        $audiences = $conn->query("
            SELECT a.id, a.name, a.description 
            FROM campaign_audience ca
            LEFT JOIN audience a ON ca.audience_id = a.id
            WHERE ca.campaign_id=$id
        ");
        $camp['audiences'] = [];
        while($aud = $audiences->fetch_assoc()) $camp['audiences'][] = $aud;
        
        jsonResponse(true, '', ['data' => $camp]);
        break;
        
    case 'delete':
        requirePermission($conn, 'campaigns', 'delete');
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $conn->query("DELETE FROM campaign WHERE id=$id AND account_id=$account_id");
        jsonResponse(true, 'Campaign deleted');
        break;
        
    case 'toggle_status':
        requirePermission($conn, 'campaigns', 'edit');
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $status = (int)($json['status'] ?? $_POST['status'] ?? 0);
        $conn->query("UPDATE campaign SET status=$status WHERE id=$id AND account_id=$account_id");
        jsonResponse(true, 'Status updated');
        break;
        
    default:
        jsonResponse(false, 'Invalid action');
}
?>