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

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

// Check if user has admin role
$pdo = hw_db();
$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);
}

$input = hw_input_json();
$name = trim((string)($input['name'] ?? ''));
$message = trim((string)($input['message'] ?? ''));
$targetAudience = $input['target_audience'] ?? 'all_users';
$locationFilter = $input['location_filter'] ?? null;
$membershipFilter = $input['membership_filter'] ?? null;
$scheduleAt = $input['schedule_at'] ?? null;

if (!$name || !$message) {
    hw_json(['success' => false, 'message' => 'Campaign name and message are required'], 422);
}

try {
    $pdo->beginTransaction();
    
    // Create campaign
    $stmt = $pdo->prepare("
        INSERT INTO sms_campaigns (name, message, target_audience, location_filter, membership_filter, scheduled_at, created_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $name,
        $message,
        $targetAudience,
        $locationFilter ? json_encode($locationFilter) : null,
        $membershipFilter ? json_encode($membershipFilter) : null,
        $scheduleAt,
        (int)$user['sub']
    ]);
    $campaignId = (int)$pdo->lastInsertId();
    
    // Get target users based on audience
    $targetUsers = [];
    
    switch ($targetAudience) {
        case 'all_users':
            $stmt = $pdo->query("
                SELECT u.id, u.first_name, p.phone_number 
                FROM users u 
                JOIN user_phone_numbers p ON u.id = p.user_id 
                WHERE p.sms_enabled = 1 AND p.is_verified = 1
            ");
            $targetUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'members_only':
            $stmt = $pdo->query("
                SELECT u.id, u.first_name, p.phone_number 
                FROM users u 
                JOIN user_phone_numbers p ON u.id = p.user_id 
                JOIN subscriptions s ON u.id = s.user_id 
                WHERE p.sms_enabled = 1 AND p.is_verified = 1 AND s.status = 'active'
            ");
            $targetUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
            
        case 'coaches':
            $stmt = $pdo->query("
                SELECT u.id, u.first_name, p.phone_number 
                FROM users u 
                JOIN user_phone_numbers p ON u.id = p.user_id 
                JOIN coaches c ON u.id = c.user_id 
                WHERE p.sms_enabled = 1 AND p.is_verified = 1
            ");
            $targetUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            break;
    }
    
    // Send messages immediately if not scheduled
    if (!$scheduleAt) {
        $sentCount = 0;
        $deliveredCount = 0;
        $failedCount = 0;
        
        foreach ($targetUsers as $targetUser) {
            try {
                // Personalize message
                $personalizedMessage = str_replace('{{first_name}}', $targetUser['first_name'], $message);
                
                // Simulate SMS sending
                $providerMessageId = 'broadcast_' . uniqid();
                $status = 'sent'; // Demo always succeeds
                $cost = 0.0075;
                
                $stmt = $pdo->prepare("
                    INSERT INTO sms_messages (user_id, phone_number, message_type, content, status, provider_message_id, cost, sent_at) 
                    VALUES (?, ?, 'broadcast', ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([
                    $targetUser['id'],
                    $targetUser['phone_number'],
                    $personalizedMessage,
                    $status,
                    $providerMessageId,
                    $cost
                ]);
                
                $sentCount++;
                $deliveredCount++; // Demo assumes delivery
            } catch (Exception $e) {
                $failedCount++;
            }
        }
        
        // Update campaign status
        $stmt = $pdo->prepare("
            UPDATE sms_campaigns 
            SET status = 'completed', sent_count = ?, delivered_count = ?, failed_count = ? 
            WHERE id = ?
        ");
        $stmt->execute([$sentCount, $deliveredCount, $failedCount, $campaignId]);
    } else {
        // Mark as scheduled
        $stmt = $pdo->prepare("UPDATE sms_campaigns SET status = 'scheduled' WHERE id = ?");
        $stmt->execute([$campaignId]);
    }
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("campaign_id", ?, "target_count", ?))')
        ->execute([(int)$user['sub'], 'sms_campaign_created', $campaignId, count($targetUsers)]);
    
    $pdo->commit();
    
    hw_json([
        'success' => true,
        'campaign_id' => $campaignId,
        'target_count' => count($targetUsers),
        'sent_count' => $sentCount ?? 0,
        'status' => $scheduleAt ? 'scheduled' : 'completed'
    ]);
} catch (Throwable $e) {
    $pdo->rollBack();
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}