<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

$type = $_GET['type'] ?? 'user'; // 'user' or 'admin'
$limit = min((int)($_GET['limit'] ?? 20), 100);
$offset = max((int)($_GET['offset'] ?? 0), 0);

try {
    $pdo = hw_db();
    
    if ($type === 'admin') {
        // Check admin access
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as count FROM user_roles ur 
            JOIN roles r ON ur.role_id = r.id 
            WHERE ur.user_id = ? AND r.name = 'admin'
        ");
        $stmt->execute([(int)$user['sub']]);
        $isAdmin = $stmt->fetch(PDO::FETCH_ASSOC)['count'] > 0;
        
        if (!$isAdmin) {
            hw_json(['success' => false, 'message' => 'Admin access required'], 403);
        }
        
        // Get admin SMS analytics
        $stmt = $pdo->query("
            SELECT 
                message_type,
                COUNT(*) as total_count,
                SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent_count,
                SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered_count,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_count,
                SUM(cost) as total_cost,
                DATE(created_at) as date
            FROM sms_messages 
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            GROUP BY message_type, DATE(created_at)
            ORDER BY date DESC, message_type
        ");
        $analytics = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get recent campaigns
        $stmt = $pdo->prepare("
            SELECT c.*, u.first_name, u.last_name 
            FROM sms_campaigns c 
            JOIN users u ON c.created_by = u.id 
            ORDER BY c.created_at DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$limit, $offset]);
        $campaigns = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get recent messages
        $stmt = $pdo->prepare("
            SELECT s.*, u.first_name, u.last_name 
            FROM sms_messages s 
            LEFT JOIN users u ON s.user_id = u.id 
            ORDER BY s.created_at DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$limit, $offset]);
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        hw_json([
            'success' => true,
            'analytics' => $analytics,
            'campaigns' => $campaigns,
            'recent_messages' => $messages
        ]);
    } else {
        // Get user's SMS history
        $stmt = $pdo->prepare("
            SELECT * FROM sms_messages 
            WHERE user_id = ? 
            ORDER BY created_at DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([(int)$user['sub'], $limit, $offset]);
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get user's phone number settings
        $stmt = $pdo->prepare("
            SELECT * FROM user_phone_numbers 
            WHERE user_id = ? 
            ORDER BY is_primary DESC, created_at DESC
        ");
        $stmt->execute([(int)$user['sub']]);
        $phoneNumbers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        hw_json([
            'success' => true,
            'messages' => $messages,
            'phone_numbers' => $phoneNumbers
        ]);
    }
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}