<?php
declare(strict_types=1);

namespace App\Modules\Notifications\Models;

use App\Core\App;
use App\Core\Pagination;

class SmsLog
{
    public static function create(array $data): int
    {
        $db = App::getInstance()->db();
        return $db->insert('sms_log', $data);
    }

    public static function search(array $filters, int $perPage = 30, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['status'])) { $where .= ' AND s.status = ?'; $params[] = $filters['status']; }
        if (!empty($filters['date_from'])) { $where .= ' AND s.created_at >= ?'; $params[] = $filters['date_from'] . ' 00:00:00'; }
        if (!empty($filters['date_to'])) { $where .= ' AND s.created_at <= ?'; $params[] = $filters['date_to'] . ' 23:59:59'; }
        if (!empty($filters['search'])) {
            $where .= ' AND (s.phone_number LIKE ? OR s.message_text LIKE ?)';
            $s = '%' . $filters['search'] . '%'; $params[] = $s; $params[] = $s;
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM sms_log s WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT s.*, m.full_name_ar as member_name FROM sms_log s LEFT JOIN members m ON m.id = s.member_id WHERE {$where} ORDER BY s.created_at DESC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return ['data' => $rows, 'pagination' => Pagination::paginate($total, $perPage, $page)];
    }

    public static function getMonthlyCost(): string
    {
        $db = App::getInstance()->db();
        $firstDay = date('Y-m-01');
        $row = $db->selectOne("SELECT COALESCE(SUM(cost), 0) as total FROM sms_log WHERE created_at >= ? AND status = 'sent'", [$firstDay]);
        return $row['total'] ?? '0.0000';
    }
}