<?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'];

// GET    /chat_rules.php               -> list all rules for this user
// GET    /chat_rules.php?active_only=1 -> only enabled rules (used by the native WhatsApp listener)
// POST   /chat_rules.php               -> create
// PUT    /chat_rules.php?id=5          -> update
// PATCH  /chat_rules.php?id=5&action=status -> enable/disable
// DELETE /chat_rules.php?id=5          -> delete

if ($method === 'GET') {
    $activeOnly = ($_GET['active_only'] ?? '') === '1';
    $where = 'user_email = :email' . ($activeOnly ? ' AND is_enabled = 1' : '');
    $stmt = $pdo->prepare("SELECT * FROM whatsapp_chat_rules WHERE $where ORDER BY created_at DESC");
    $stmt->execute([':email' => $authUser['email']]);
    send_success(['rules' => $stmt->fetchAll()]);
}

if ($method === 'POST') {
    $input = get_json_input();
    require_fields($input, ['received_keywords', 'reply_message']);

    $stmt = $pdo->prepare(
        'INSERT INTO whatsapp_chat_rules (user_email, received_keywords, reply_message, match_type, target_app,
                                           is_enabled, is_welcome_message, reply_delay_seconds)
         VALUES (:email, :keywords, :reply, :match_type, :target, :enabled, :welcome, :delay)'
    );
    $stmt->execute([
        ':email'    => $authUser['email'],
        ':keywords' => clean_str($input['received_keywords']),
        ':reply'    => clean_str($input['reply_message']),
        ':match_type' => clean_str($input['match_type'] ?? 'CONTAINS'),
        ':target'   => clean_str($input['target_app'] ?? 'ALL'),
        ':enabled'  => isset($input['is_enabled']) ? (int) (bool) $input['is_enabled'] : 1,
        ':welcome'  => isset($input['is_welcome_message']) ? (int) (bool) $input['is_welcome_message'] : 0,
        ':delay'    => (int) ($input['reply_delay_seconds'] ?? 1),
    ]);

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

if ($method === 'PUT' && isset($_GET['id'])) {
    $input = get_json_input();
    $allowed = ['received_keywords', 'reply_message', 'match_type', 'target_app', 'reply_delay_seconds'];
    $fields = [];
    $params = [':id' => (int) $_GET['id'], ':email' => $authUser['email']];
    foreach ($allowed 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 whatsapp_chat_rules SET ' . implode(', ', $fields) . ' WHERE id = :id AND user_email = :email');
    $stmt->execute($params);
    send_success(null, 'Rule updated.');
}

if ($method === 'PATCH' && isset($_GET['id']) && ($_GET['action'] ?? '') === 'status') {
    $input = get_json_input();
    require_fields($input, ['is_enabled']);
    $stmt = $pdo->prepare('UPDATE whatsapp_chat_rules SET is_enabled = :enabled WHERE id = :id AND user_email = :email');
    $stmt->execute([':enabled' => $input['is_enabled'] ? 1 : 0, ':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Rule status updated.');
}

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

send_error('Invalid request.', 400);
