<?php
session_start();
header('Content-Type: application/json');

// Include database connection
include '../layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not authenticated']);
    exit();
}

// Check permissions
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'communications_view') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Validate POST data
if (!isset($_POST['agent_id']) || !isset($_POST['message_type']) || !isset($_POST['subject']) || !isset($_POST['message'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

$agent_id = (int)$_POST['agent_id'];
$message_type = $_POST['message_type'];
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);

// Validate message type
$valid_types = ['EMAIL', 'SMS', 'WHATSAPP'];
if (!in_array($message_type, $valid_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid message type']);
    exit();
}

// Validate content
if (empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'Subject and message are required']);
    exit();
}

try {
    $conn->begin_transaction();
    
    // Get agent information
    $agent_sql = "SELECT u.full_name, u.email, u.phone_number, u.agent_code 
                  FROM users u 
                  WHERE u.user_id = ? AND u.agent_code IS NOT NULL";
    $agent_stmt = $conn->prepare($agent_sql);
    $agent_stmt->bind_param("i", $agent_id);
    $agent_stmt->execute();
    $agent_info = $agent_stmt->get_result()->fetch_assoc();
    
    if (!$agent_info) {
        throw new Exception('Agent not found');
    }
    
    // Determine recipient contact based on message type
    $recipient_contact = '';
    switch ($message_type) {
        case 'EMAIL':
            $recipient_contact = $agent_info['email'];
            break;
        case 'SMS':
        case 'WHATSAPP':
            $recipient_contact = $agent_info['phone_number'];
            break;
    }
    
    if (empty($recipient_contact)) {
        throw new Exception("Agent's {$message_type} contact information not available");
    }
    
    // Insert message into communication log
    $insert_sql = "INSERT INTO communication_log (
        recipient_type, recipient_id, communication_type, subject, message, 
        recipient_contact, status, sent_by, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?, CURRENT_TIMESTAMP)";
    
    $insert_stmt = $conn->prepare($insert_sql);
    $recipient_type = 'AGENT';
    $insert_stmt->bind_param("sisssi", $recipient_type, $agent_id, $message_type, 
                           $subject, $message, $recipient_contact, $user_id);
    
    if (!$insert_stmt->execute()) {
        throw new Exception('Failed to queue message');
    }
    
    $message_id = $conn->insert_id;
    
    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values) 
               VALUES (?, 'SEND_MESSAGE', 'COMMUNICATION', ?, 'MESSAGE', ?)";
    $log_stmt = $conn->prepare($log_sql);
    
    $log_data = json_encode([
        'message_type' => $message_type,
        'recipient' => $agent_info['full_name'],
        'agent_code' => $agent_info['agent_code'],
        'subject' => $subject,
        'sent_by' => $_SESSION['full_name']
    ]);
    
    $log_stmt->bind_param("iis", $user_id, $message_id, $log_data);
    $log_stmt->execute();
    
    // Here you would typically integrate with actual messaging services
    // For now, we'll simulate sending and mark as sent
    $update_sql = "UPDATE communication_log SET status = 'SENT', sent_at = CURRENT_TIMESTAMP WHERE log_id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("i", $message_id);
    $update_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Message sent successfully',
        'message_id' => $message_id,
        'recipient' => $agent_info['full_name']
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>