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

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

$user_id = $_SESSION['user_id'];

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

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

    // Total for this user
    $totalStmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ?");
    $totalStmt->execute([$user_id]);
    $totalRecords = $totalStmt->fetchColumn();

    // Build query
    $sql = "SELECT * FROM sms_logs WHERE user_id = ?";
    $params = [$user_id];

    if (!empty($searchValue)) {
        $sql .= " AND (recipient_number LIKE ? OR message_body LIKE ?)";
        $params[] = "%$searchValue%";
        $params[] = "%$searchValue%";
    }
    if (!empty($status_filter)) {
        $sql .= " AND status = ?";
        $params[] = $status_filter;
    }
    if (!empty($date_from)) {
        $sql .= " AND DATE(sent_at) >= ?";
        $params[] = $date_from;
    }
    if (!empty($date_to)) {
        $sql .= " AND DATE(sent_at) <= ?";
        $params[] = $date_to;
    }

    // Filtered count
    $filteredSql = str_replace("SELECT *", "SELECT COUNT(*)", $sql);
    $filteredStmt = $pdo->prepare($filteredSql);
    $filteredStmt->execute($params);
    $filteredRecords = $filteredStmt->fetchColumn();

    $sql .= " ORDER BY $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>';

        $clean = preg_replace('/[^0-9]/', '', $log['recipient_number']);
        $waNum = (strpos($clean, '88') === 0) ? $clean : '88' . $clean;

        $data[] = [
            $log['id'],
            htmlspecialchars($log['recipient_number']) .
            ' <a href="https://wa.me/' . $waNum . '" target="_blank" class="btn btn-sm btn-success ms-1" title="WhatsApp"><i class="fab fa-whatsapp"></i></a>' .
            ' <a href="tel:' . htmlspecialchars($log['recipient_number']) . '" class="btn btn-sm btn-primary ms-1"><i class="fa fa-phone"></i></a>',
            '<textarea class="form-control" readonly style="height:80px;resize:none;font-size:0.8rem;">' . htmlspecialchars($log['message_body']) . '</textarea>',
            $statusBadge,
            $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()]);
}
