<?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);

$input = hw_input_json();
$phoneNumber = trim((string)($input['phone_number'] ?? ''));
$messageType = $input['message_type'] ?? 'system';
$templateName = $input['template_name'] ?? '';
$variables = $input['variables'] ?? [];
$customMessage = $input['custom_message'] ?? '';

if (!$phoneNumber) hw_json(['success' => false, 'message' => 'phone_number is required'], 422);

try {
    $pdo = hw_db();
    
    $messageContent = '';
    
    if ($templateName) {
        // Use template
        $stmt = $pdo->prepare("SELECT * FROM sms_templates WHERE name = ? AND active = 1");
        $stmt->execute([$templateName]);
        $template = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$template) {
            hw_json(['success' => false, 'message' => 'Template not found'], 404);
        }
        
        $messageContent = $template['template'];
        
        // Replace variables
        foreach ($variables as $key => $value) {
            $messageContent = str_replace('{{' . $key . '}}', $value, $messageContent);
        }
    } else {
        $messageContent = $customMessage;
    }
    
    if (!$messageContent) {
        hw_json(['success' => false, 'message' => 'Message content is required'], 422);
    }
    
    // Simulate SMS sending (in production, integrate with Twilio, AWS SNS, etc.)
    $providerMessageId = 'demo_' . uniqid();
    $status = 'sent'; // Demo always succeeds
    $cost = 0.0075; // $0.0075 per SMS
    
    // Store SMS record
    $stmt = $pdo->prepare("
        INSERT INTO sms_messages (user_id, phone_number, message_type, content, status, provider_message_id, cost, sent_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
        (int)$user['sub'],
        $phoneNumber,
        $messageType,
        $messageContent,
        $status,
        $providerMessageId,
        $cost
    ]);
    $messageId = (int)$pdo->lastInsertId();
    
    // Audit log
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("sms_id", ?, "phone", ?, "type", ?))')
        ->execute([(int)$user['sub'], 'sms_sent', $messageId, $phoneNumber, $messageType]);
    
    hw_json([
        'success' => true,
        'message_id' => $messageId,
        'provider_message_id' => $providerMessageId,
        'status' => $status,
        'cost' => $cost
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}