<?php
/**
 * API: Create new member assignment
 * 
 * This endpoint assigns a member to an admin for review
 */

require_once '../../config/database.php';
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => null,
    'message' => 'Error creating assignment'
];

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Method not allowed';
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

try {
    // Get POST data
    $postData = json_decode(file_get_contents('php://input'), true);
    if (!$postData) {
        $postData = $_POST;
    }
    
    // Validate required fields
    $requiredFields = ['member_id', 'assigned_to', 'assignment_type', 'priority'];
    foreach ($requiredFields as $field) {
        if (!isset($postData[$field]) || empty($postData[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    $db = new Database();
    $conn = $db->getConnection();
    
    // Start transaction
    $conn->beginTransaction();
    
    // Insert assignment
    $query = "INSERT INTO admin_assignments 
              (member_id, assigned_to, assigned_by, assignment_type, priority, due_date, status, notes) 
              VALUES 
              (:member_id, :assigned_to, :assigned_by, :assignment_type, :priority, :due_date, 'active', :notes)";
    
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':member_id', $postData['member_id']);
    $stmt->bindValue(':assigned_to', $postData['assigned_to']);
    $stmt->bindValue(':assigned_by', $_SESSION['admin_id']); // Get from session
    $stmt->bindValue(':assignment_type', $postData['assignment_type']);
    $stmt->bindValue(':priority', $postData['priority']);
    $stmt->bindValue(':due_date', isset($postData['due_date']) ? $postData['due_date'] : null);
    $stmt->bindValue(':notes', isset($postData['notes']) ? $postData['notes'] : null);
    $stmt->execute();
    
    $assignmentId = $conn->lastInsertId();
    
    // Update member assigned_to field
    $updateMemberQuery = "UPDATE members 
                         SET assigned_to = :assigned_to, 
                             assignment_notes = :notes, 
                             assignment_date = NOW() 
                         WHERE id = :member_id";
    $updateMemberStmt = $conn->prepare($updateMemberQuery);
    $updateMemberStmt->bindValue(':assigned_to', $postData['assigned_to']);
    $updateMemberStmt->bindValue(':notes', isset($postData['notes']) ? $postData['notes'] : null);
    $updateMemberStmt->bindValue(':member_id', $postData['member_id']);
    $updateMemberStmt->execute();
    
    // Add to member approval history
    $historyQuery = "INSERT INTO member_approval_history 
                     (member_id, action, performed_by, from_status, to_status, assigned_from, assigned_to, notes, ip_address) 
                     VALUES 
                     (:member_id, 'assigned', :performed_by, 
                      (SELECT status FROM members WHERE id = :member_id), 
                      'under_review', 
                      NULL, :assigned_to, :notes, :ip_address)";
    $historyStmt = $conn->prepare($historyQuery);
    $historyStmt->bindValue(':member_id', $postData['member_id']);
    $historyStmt->bindValue(':performed_by', $_SESSION['admin_id']);
    $historyStmt->bindValue(':assigned_to', $postData['assigned_to']);
    $historyStmt->bindValue(':notes', isset($postData['notes']) ? $postData['notes'] : null);
    $historyStmt->bindValue(':ip_address', $_SERVER['REMOTE_ADDR']);
    $historyStmt->execute();
    
    // Create notification for the assigned admin
    if (isset($postData['send_notification']) && $postData['send_notification']) {
        // Get member name
        $memberQuery = "SELECT CONCAT(first_name, ' ', last_name) as member_name FROM members WHERE id = :member_id";
        $memberStmt = $conn->prepare($memberQuery);
        $memberStmt->bindValue(':member_id', $postData['member_id']);
        $memberStmt->execute();
        $memberName = $memberStmt->fetch(PDO::FETCH_ASSOC)['member_name'];
        
        // Create notification
        $notificationQuery = "INSERT INTO notifications 
                             (type, title, message, target_audience, target_user_id, created_by, priority, related_entity_type, related_entity_id) 
                             VALUES 
                             ('info', :title, :message, 'specific', :target_user_id, :created_by, :priority, 'member', :member_id)";
        $notificationStmt = $conn->prepare($notificationQuery);
        $notificationStmt->bindValue(':title', 'New Member Assignment');
        $notificationStmt->bindValue(':message', "You have been assigned to review the member: $memberName. Please review their information and take appropriate action.");
        $notificationStmt->bindValue(':target_user_id', $postData['assigned_to']);
        $notificationStmt->bindValue(':created_by', $_SESSION['admin_id']);
        $notificationStmt->bindValue(':priority', $postData['priority']);
        $notificationStmt->bindValue(':member_id', $postData['member_id']);
        $notificationStmt->execute();
        
        $notificationId = $conn->lastInsertId();
        
        // Add notification recipient
        $recipientQuery = "INSERT INTO notification_recipients 
                          (notification_id, user_id, user_type) 
                          VALUES 
                          (:notification_id, :user_id, 'admin')";
        $recipientStmt = $conn->prepare($recipientQuery);
        $recipientStmt->bindValue(':notification_id', $notificationId);
        $recipientStmt->bindValue(':user_id', $postData['assigned_to']);
        $recipientStmt->execute();
    }
    
    // Commit transaction
    $conn->commit();
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'assignment_id' => $assignmentId,
            'member_id' => $postData['member_id'],
            'assigned_to' => $postData['assigned_to']
        ],
        'message' => 'Member assigned successfully'
    ];
    
} catch (PDOException $e) {
    // Rollback transaction on error
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Error: ' . $e->getMessage();
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
