<?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(?, 'agent_performance') 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['feedback_type']) || !isset($_POST['subject']) || !isset($_POST['message'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit();
}

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

// Validate feedback type
$valid_types = ['RECOGNITION', 'IMPROVEMENT', 'COACHING', 'GOAL_SETTING'];
if (!in_array($feedback_type, $valid_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid feedback 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.agent_code, u.supervisor_id
                  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');
    }
    
    // Prepare feedback message with performance context
    $feedback_templates = [
        'RECOGNITION' => 'Performance Recognition',
        'IMPROVEMENT' => 'Performance Improvement Plan',
        'COACHING' => 'Coaching & Development',
        'GOAL_SETTING' => 'Goal Setting & Target Review'
    ];
    
    $email_subject = $feedback_templates[$feedback_type] . ': ' . $subject;
    $email_message = "Dear {$agent_info['full_name']},\n\n";
    $email_message .= "You have received performance feedback from {$_SESSION['full_name']}.\n\n";
    $email_message .= "Feedback Type: " . str_replace('_', ' ', $feedback_type) . "\n";
    $email_message .= "Subject: $subject\n\n";
    $email_message .= "Message:\n$message\n\n";
    
    if ($feedback_type === 'RECOGNITION') {
        $email_message .= "Congratulations on your excellent performance! Keep up the great work.\n\n";
    } elseif ($feedback_type === 'IMPROVEMENT') {
        $email_message .= "This feedback is intended to help you improve your performance. Please discuss this with your supervisor if you have any questions.\n\n";
    } elseif ($feedback_type === 'COACHING') {
        $email_message .= "We're here to support your professional development. Please reach out if you need additional training or resources.\n\n";
    } elseif ($feedback_type === 'GOAL_SETTING') {
        $email_message .= "Let's work together to achieve your targets. Please review and discuss these goals with your supervisor.\n\n";
    }
    
    $email_message .= "If you have any questions or would like to discuss this feedback, please don't hesitate to reach out.\n\n";
    $email_message .= "Best regards,\n";
    $email_message .= "{$_SESSION['full_name']}\n";
    $email_message .= "Ultrasure Insurance Platform";
    
    // Insert feedback into communication log
    $comm_sql = "INSERT INTO communication_log (
        recipient_type, recipient_id, communication_type, subject, message, 
        recipient_contact, status, sent_by, created_at
    ) VALUES ('AGENT', ?, 'EMAIL', ?, ?, ?, 'PENDING', ?, CURRENT_TIMESTAMP)";
    
    $comm_stmt = $conn->prepare($comm_sql);
    $comm_stmt->bind_param("isssi", $agent_id, $email_subject, $email_message, 
                          $agent_info['email'], $user_id);
    $comm_stmt->execute();
    
    $communication_id = $conn->insert_id();
    
    // Also send copy to supervisor if exists
    if ($agent_info['supervisor_id']) {
        $supervisor_sql = "SELECT email, full_name FROM users WHERE user_id = ?";
        $supervisor_stmt = $conn->prepare($supervisor_sql);
        $supervisor_stmt->bind_param("i", $agent_info['supervisor_id']);
        $supervisor_stmt->execute();
        $supervisor_info = $supervisor_stmt->get_result()->fetch_assoc();
        
        if ($supervisor_info) {
            $supervisor_subject = "Performance Feedback Sent to " . $agent_info['full_name'];
            $supervisor_message = "Dear {$supervisor_info['full_name']},\n\n";
            $supervisor_message .= "Performance feedback has been sent to {$agent_info['full_name']} ({$agent_info['agent_code']}).\n\n";
            $supervisor_message .= "Feedback Type: " . str_replace('_', ' ', $feedback_type) . "\n";
            $supervisor_message .= "Subject: $subject\n\n";
            $supervisor_message .= "You may want to follow up with the agent to discuss this feedback.\n\n";
            $supervisor_message .= "Best regards,\n";
            $supervisor_message .= "Ultrasure Insurance Platform";
            
            $supervisor_comm_sql = "INSERT INTO communication_log (
                recipient_type, recipient_id, communication_type, subject, message, 
                recipient_contact, status, sent_by, created_at
            ) VALUES ('USER', ?, 'EMAIL', ?, ?, ?, 'PENDING', ?, CURRENT_TIMESTAMP)";
            
            $supervisor_comm_stmt = $conn->prepare($supervisor_comm_sql);
            $supervisor_comm_stmt->bind_param("isssi", $agent_info['supervisor_id'], $supervisor_subject, 
                                            $supervisor_message, $supervisor_info['email'], $user_id);
            $supervisor_comm_stmt->execute();
        }
    }
    
    // Log the activity
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
               VALUES (?, 'PERFORMANCE_FEEDBACK', 'AGENT', ?, 'FEEDBACK', ?, ?, ?)";
    $log_stmt = $conn->prepare($log_sql);
    
    $log_data = json_encode([
        'feedback_type' => $feedback_type,
        'agent_name' => $agent_info['full_name'],
        'agent_code' => $agent_info['agent_code'],
        'subject' => $subject,
        'sent_by' => $_SESSION['full_name']
    ]);
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    $log_stmt->bind_param("iissss", $user_id, $agent_id, $log_data, $ip_address, $user_agent);
    $log_stmt->execute();
    
    // Mark emails as sent (in a real implementation, you'd integrate with email service)
    $update_comm_sql = "UPDATE communication_log SET status = 'SENT', sent_at = CURRENT_TIMESTAMP WHERE log_id >= ?";
    $update_comm_stmt = $conn->prepare($update_comm_sql);
    $update_comm_stmt->bind_param("i", $communication_id);
    $update_comm_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Performance feedback sent successfully',
        'agent_name' => $agent_info['full_name'],
        'feedback_type' => $feedback_type
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

$conn->close();
?>