<?php
require_once '../../config.php';
require_once '../../functions.php';

header('Content-Type: application/json');
check_admin_auth();

try {
    $draw = intval($_GET['draw'] ?? 1);
    $start = intval($_GET['start'] ?? 0);
    $length = intval($_GET['length'] ?? 10);
    $searchValue = $_GET['search']['value'] ?? '';
    $orderColumnIndex = intval($_GET['order'][0]['column'] ?? 0);
    $orderDir = strtoupper($_GET['order'][0]['dir'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';

    // New filters
    $user_filter = $_GET['user_filter'] ?? '';
    $status_filter = $_GET['status_filter'] ?? '';
    $date_from = $_GET['date_from'] ?? '';
    $date_to = $_GET['date_to'] ?? '';

    $columns = ['id', 'username', 'recipient_number', 'message_body', 'sent_at'];
    $orderColumn = $columns[$orderColumnIndex] ?? 'sent_at';

    $totalQuery = "SELECT COUNT(*) as total FROM sms_logs";
    $totalRecords = $pdo->query($totalQuery)->fetch()['total'];

    $sql = "SELECT sms_logs.*, users.username FROM sms_logs LEFT JOIN users ON sms_logs.user_id = users.id";
    $where = [];
    $params = [];

    if (!empty($searchValue)) {
        $where[] = "(sms_logs.recipient_number LIKE ? OR sms_logs.message_body LIKE ? OR users.username LIKE ? OR sms_logs.status LIKE ?)";
        $sp = "%$searchValue%";
        $params = array_merge($params, [$sp, $sp, $sp, $sp]);
    }
    if (!empty($user_filter)) {
        $where[] = "sms_logs.user_id = ?";
        $params[] = $user_filter;
    }
    if (!empty($status_filter)) {
        $where[] = "sms_logs.status = ?";
        $params[] = $status_filter;
    }
    if (!empty($date_from)) {
        $where[] = "DATE(sms_logs.sent_at) >= ?";
        $params[] = $date_from;
    }
    if (!empty($date_to)) {
        $where[] = "DATE(sms_logs.sent_at) <= ?";
        $params[] = $date_to;
    }

    if (!empty($where))
        $sql .= " WHERE " . implode(" AND ", $where);

    // Filtered count
    $filteredSql = "SELECT COUNT(*) as total FROM sms_logs LEFT JOIN users ON sms_logs.user_id = users.id";
    if (!empty($where))
        $filteredSql .= " WHERE " . implode(" AND ", $where);
    $fStmt = $pdo->prepare($filteredSql);
    $fStmt->execute($params);
    $filteredRecords = $fStmt->fetch()['total'];

    $sql .= " ORDER BY sms_logs.$orderColumn $orderDir LIMIT $start, $length";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $data = [];
    foreach ($logs as $log) {
        $statusBadge = $log['status'] == 'sent'
            ? '<span class="badge bg-success">sent</span>'
            : '<span class="badge bg-danger">' . htmlspecialchars($log['status']) . '</span>';

        $userStatus = '<div><strong>' . htmlspecialchars($log['username'] ?? 'System') . '</strong></div><div class="mt-1">' . $statusBadge . '</div>';

        $clean = preg_replace('/[^0-9]/', '', $log['recipient_number']);
        $waNum = (strpos($clean, '88') === 0) ? $clean : '88' . $clean;
        $actions = '<a href="https://wa.me/' . $waNum . '" target="_blank" class="btn btn-sm btn-success me-1"><i class="fab fa-whatsapp"></i></a>' .
            '<a href="tel:' . htmlspecialchars($log['recipient_number']) . '" class="btn btn-sm btn-primary"><i class="fa fa-phone"></i></a>';
        $mobileActions = '<div><strong>' . htmlspecialchars($log['recipient_number']) . '</strong></div><div class="mt-1">' . $actions . '</div>';

        $msgArea = '<textarea class="form-control" readonly style="height:80px;resize:none;font-size:0.8rem;">' . htmlspecialchars($log['message_body']) . '</textarea>';

        $data[] = [$log['id'], $userStatus, $mobileActions, $msgArea, $log['sent_at']];
    }

    echo json_encode(['draw' => $draw, 'recordsTotal' => $totalRecords, 'recordsFiltered' => $filteredRecords, 'data' => $data]);

} catch (Exception $e) {
    echo json_encode(['draw' => 1, 'recordsTotal' => 0, 'recordsFiltered' => 0, 'data' => [], 'error' => $e->getMessage()]);
}
