<?php
/**
 * Update Report Status AJAX Handler
 * GHAMECC Choir Management Platform
 * 
 * This script handles AJAX requests to update report status (approve/reject/complete)
 * and add responses to reports.
 */

// Include authentication functions
require_once '../../includes/auth.php';

// Require login
requireLogin();

// Initialize response array
$response = [
    'success' => false,
    'message' => '',
    'data' => null
];

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request method';
    echo json_encode($response);
    exit;
}

// Get user information
$userId = $_SESSION['user_id'];

// Get report ID
$reportId = isset($_POST['report_id']) ? (int)$_POST['report_id'] : 0;
if ($reportId <= 0) {
    $response['message'] = 'Invalid report ID';
    echo json_encode($response);
    exit;
}

// Get action type
$action = isset($_POST['action']) ? $_POST['action'] : '';
if (!in_array($action, ['approve', 'reject', 'complete', 'respond'])) {
    $response['message'] = 'Invalid action';
    echo json_encode($response);
    exit;
}

// Get report information
$report = fetchRow("SELECT * FROM reports WHERE id = $reportId");
if (!$report) {
    $response['message'] = 'Report not found';
    echo json_encode($response);
    exit;
}

// Check if user has permission to update this report
$hasPermission = false;

// Check if user is associated with the target entity
if ($report['target_type'] === 'society') {
    // Check if user has a role in this society
    $societyRole = fetchRow("SELECT * FROM society_roles WHERE user_id = $userId AND society_id = {$report['target_id']}");
    if ($societyRole) {
        $hasPermission = true;
    }
} elseif ($report['target_type'] === 'circuit') {
    // Check if user has a role in this circuit
    $circuitRole = fetchRow("SELECT * FROM circuit_roles WHERE user_id = $userId AND circuit_id = {$report['target_id']}");
    if ($circuitRole) {
        $hasPermission = true;
    }
} elseif ($report['target_type'] === 'diocese') {
    // Check if user has a role in this diocese
    $dioceseRole = fetchRow("SELECT * FROM diocese_roles WHERE user_id = $userId AND diocese_id = {$report['target_id']}");
    if ($dioceseRole) {
        $hasPermission = true;
    }
} elseif ($report['target_type'] === 'connexional') {
    // Check if user is an admin
    if (hasRole(['admin'])) {
        $hasPermission = true;
    }
}

// Also allow report creator to respond to their own report
if ($action === 'respond' && $report['user_id'] === $userId) {
    $hasPermission = true;
}

// Check permission
if (!$hasPermission) {
    $response['message'] = 'You do not have permission to perform this action';
    echo json_encode($response);
    exit;
}

// Process the action
switch ($action) {
    case 'approve':
        // Update report status to approved
        $updateQuery = "UPDATE reports SET status = 'approved', updated_at = NOW() WHERE id = $reportId";
        if (executeQuery($updateQuery)) {
            // Add system response for approval
            $content = "This report has been approved.";
            $insertResponse = "INSERT INTO report_responses (report_id, user_id, content, created_at) 
                              VALUES ($reportId, $userId, '" . escapeString($content) . "', NOW())";
            executeQuery($insertResponse);
            
            $response['success'] = true;
            $response['message'] = 'Report approved successfully';
        } else {
            $response['message'] = 'Failed to approve report';
        }
        break;
        
    case 'reject':
        // Get rejection reason
        $reason = isset($_POST['reason']) ? $_POST['reason'] : '';
        if (empty($reason)) {
            $response['message'] = 'Rejection reason is required';
            echo json_encode($response);
            exit;
        }
        
        // Update report status to rejected
        $updateQuery = "UPDATE reports SET status = 'rejected', updated_at = NOW() WHERE id = $reportId";
        if (executeQuery($updateQuery)) {
            // Add response with rejection reason
            $content = "This report has been rejected for the following reason:\n\n" . $reason;
            $insertResponse = "INSERT INTO report_responses (report_id, user_id, content, created_at) 
                              VALUES ($reportId, $userId, '" . escapeString($content) . "', NOW())";
            executeQuery($insertResponse);
            
            $response['success'] = true;
            $response['message'] = 'Report rejected successfully';
        } else {
            $response['message'] = 'Failed to reject report';
        }
        break;
        
    case 'complete':
        // Update report status to completed
        $updateQuery = "UPDATE reports SET status = 'completed', updated_at = NOW() WHERE id = $reportId";
        if (executeQuery($updateQuery)) {
            // Add system response for completion
            $content = "This report has been marked as completed.";
            $insertResponse = "INSERT INTO report_responses (report_id, user_id, content, created_at) 
                              VALUES ($reportId, $userId, '" . escapeString($content) . "', NOW())";
            executeQuery($insertResponse);
            
            $response['success'] = true;
            $response['message'] = 'Report marked as completed';
        } else {
            $response['message'] = 'Failed to mark report as completed';
        }
        break;
        
    case 'respond':
        // Get response content
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        if (empty($content)) {
            $response['message'] = 'Response content is required';
            echo json_encode($response);
            exit;
        }
        
        // Process file upload if present
        $attachment = '';
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
            $allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
                            'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                            'image/jpeg', 'image/png', 'image/gif'];
            $fileType = $_FILES['attachment']['type'];
            
            if (!in_array($fileType, $allowedTypes)) {
                $response['message'] = 'Invalid file type. Allowed types: PDF, DOC, DOCX, XLS, XLSX, JPG, PNG, GIF';
                echo json_encode($response);
                exit;
            }
            
            // Create uploads directory if it doesn't exist
            $uploadDir = '../../uploads/reports/responses/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            // Generate unique filename
            $fileName = uniqid('response_') . '_' . basename($_FILES['attachment']['name']);
            $uploadPath = $uploadDir . $fileName;
            
            // Move uploaded file
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadPath)) {
                $attachment = $fileName;
            } else {
                $response['message'] = 'Failed to upload attachment';
                echo json_encode($response);
                exit;
            }
        }
        
        // Add response
        $insertResponse = "INSERT INTO report_responses (report_id, user_id, content, attachment, created_at) 
                          VALUES ($reportId, $userId, '" . escapeString($content) . "', '" . escapeString($attachment) . "', NOW())";
        
        if (executeQuery($insertResponse)) {
            $response['success'] = true;
            $response['message'] = 'Response added successfully';
            
            // Get the newly added response
            $newResponseId = getLastInsertId();
            $newResponse = fetchRow("SELECT rr.*, u.full_name, u.profile_image 
                                    FROM report_responses rr 
                                    JOIN users u ON rr.user_id = u.id 
                                    WHERE rr.id = $newResponseId");
            
            if ($newResponse) {
                // Format the response for display
                $formattedResponse = [
                    'id' => $newResponse['id'],
                    'content' => nl2br(htmlspecialchars($newResponse['content'])),
                    'created_at' => date('M d, Y h:i A', strtotime($newResponse['created_at'])),
                    'user_name' => htmlspecialchars($newResponse['full_name']),
                    'user_image' => $newResponse['profile_image'],
                    'attachment' => $newResponse['attachment']
                ];
                
                $response['data'] = $formattedResponse;
            }
        } else {
            $response['message'] = 'Failed to add response';
        }
        break;
}

// Return JSON response
echo json_encode($response);
exit;
?>
