<?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') {
    $search = clean_str($_GET['search'] ?? '');
    $where = 'user_email = :email';
    $params = [':email' => $authUser['email']];
    if ($search !== '') {
        $where .= ' AND (phone_number LIKE :search OR contact_name LIKE :search2)';
        $params[':search'] = "%$search%";
        $params[':search2'] = "%$search%";
    }
    $stmt = $pdo->prepare("SELECT * FROM blacklists WHERE $where ORDER BY created_at DESC");
    $stmt->execute($params);
    send_success(['blacklist' => $stmt->fetchAll()]);
}

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

    $stmt = $pdo->prepare(
        'INSERT INTO blacklists (user_email, phone_number, contact_name, reason) VALUES (:email, :phone, :name, :reason)'
    );
    $stmt->execute([
        ':email'  => $authUser['email'],
        ':phone'  => clean_str($input['phone_number']),
        ':name'   => clean_str($input['contact_name'] ?? ''),
        ':reason' => clean_str($input['reason'] ?? 'User requested exclusion'),
    ]);

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

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

send_error('Invalid request.', 400);
