<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $stmt = $pdo->prepare('SELECT * FROM campaigns WHERE user_email = :email ORDER BY created_at DESC');
    $stmt->execute([':email' => $authUser['email']]);
    send_success(['campaigns' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['title', 'channel', 'message_template']);

    $stmt = $pdo->prepare(
        'INSERT INTO campaigns (user_email, title, channel, message_template, total_contacts, status, media_url)
         VALUES (:email, :title, :channel, :message, :total, :status, :media)'
    );
    $stmt->execute([
        ':email'   => $authUser['email'],
        ':title'   => clean_str($input['title']),
        ':channel' => clean_str($input['channel']),
        ':message' => clean_str($input['message_template']),
        ':total'   => (int) ($input['total_contacts'] ?? 0),
        ':status'  => clean_str($input['status'] ?? 'DRAFT'),
        ':media'   => clean_str($input['media_url'] ?? ''),
    ]);

    send_success(['id' => (int) $pdo->lastInsertId()], 'Campaign created.', 201);
}

if ($method === 'PATCH' && isset($_GET['id'])) {
    $input = get_json_input();
    $fields = [];
    $params = [':id' => (int) $_GET['id'], ':email' => $authUser['email']];
    foreach (['status', 'sent_count'] as $f) {
        if (isset($input[$f])) { $fields[] = "$f = :$f"; $params[":$f"] = $input[$f]; }
    }
    if (empty($fields)) send_error('No fields to update.', 422);

    $stmt = $pdo->prepare('UPDATE campaigns SET ' . implode(', ', $fields) . ' WHERE id = :id AND user_email = :email');
    $stmt->execute($params);
    send_success(null, 'Campaign updated.');
}

if ($method === 'DELETE' && isset($_GET['id'])) {
    $stmt = $pdo->prepare('DELETE FROM campaigns WHERE id = :id AND user_email = :email');
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Campaign deleted.');
}

send_error('Invalid request.', 400);
