<?php
/**
 * AJAX Handler - Submit Report Response
 * GHAMECC Choir Management Platform
 */

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

// Include database functions
require_once '../../config/database.php';

// Set JSON response header
header('Content-Type: application/json');

// Log the start of response submission
logInfo("Response submission started", [
    'request_method' => $_SERVER['REQUEST_METHOD'],
    'post_data_keys' => array_keys($_POST ?? []),
    'files_data_keys' => array_keys($_FILES ?? [])
]);

// Require login
requireLogin();

// Get user information and role
$userId = $_SESSION['user_id'];
$userInfo = fetchRow("SELECT u.*, r.role_key FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?", [$userId]);

logInfo("User information retrieved for response submission", [
    'user_id' => $userId,
    'role_key' => $userInfo['role_key'] ?? 'unknown'
]);

// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    logError("Invalid request method for response submission", ['method' => $_SERVER['REQUEST_METHOD']]);
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validate required fields
if (!isset($_POST['report_id']) || !isset($_POST['response_text'])) {
    logError("Missing required fields for response submission", [
        'has_report_id' => isset($_POST['report_id']),
        'has_response_text' => isset($_POST['response_text']),
        'post_keys' => array_keys($_POST)
    ]);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$reportId = (int)$_POST['report_id'];
$responseText = trim($_POST['response_text']);

logInfo("Response submission data validated", [
    'report_id' => $reportId,
    'response_text_length' => strlen($responseText)
]);

if (empty($responseText)) {
    logError("Empty response text provided", ['report_id' => $reportId]);
    echo json_encode(['success' => false, 'message' => 'Response text cannot be empty']);
    exit;
}

// Verify the report exists and user has permission to respond
$report = fetchRow("SELECT * FROM reports WHERE id = ?", [$reportId]);
if (!$report) {
    logError("Report not found for response submission", ['report_id' => $reportId, 'user_id' => $userId]);
    echo json_encode(['success' => false, 'message' => 'Report not found']);
    exit;
}

logInfo("Report found for response submission", [
    'report_id' => $reportId,
    'report_title' => $report['title'] ?? 'unknown',
    'report_status' => $report['status'] ?? 'unknown'
]);

// Check if report_responses table exists
$tableExistsQuery = "SHOW TABLES LIKE 'report_responses'";
$tableExists = $conn->query($tableExistsQuery);
$tableExistsBefore = $tableExists && $tableExists->num_rows > 0;

logInfo("Checking if report_responses table exists", [
    'table_exists_before_creation' => $tableExistsBefore,
    'query_result_rows' => $tableExists ? $tableExists->num_rows : 'query_failed'
]);

// Create report_responses table if it doesn't exist
$createTableSQL = "CREATE TABLE IF NOT EXISTS `report_responses` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `report_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `response_text` text NOT NULL,
  `attachment` varchar(255) DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_report_id` (`report_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";

try {
    logInfo("Attempting to create report_responses table", ['sql_length' => strlen($createTableSQL)]);
    
    $createResult = $conn->query($createTableSQL);
    
    if ($createResult) {
        logInfo("Table creation query executed successfully", ['result' => true]);
    } else {
        logError("Table creation query failed", [
            'error' => $conn->error,
            'errno' => $conn->errno
        ]);
    }
    
    // Check if table exists after creation attempt
    $tableExistsAfter = $conn->query($tableExistsQuery);
    $tableExistsAfterCreation = $tableExistsAfter && $tableExistsAfter->num_rows > 0;
    
    logInfo("Table existence check after creation", [
        'table_exists_after_creation' => $tableExistsAfterCreation,
        'creation_was_successful' => $createResult ? true : false
    ]);
    
    // Add foreign key constraints if they don't exist (only if table was created successfully)
    if ($tableExistsAfterCreation) {
        $addConstraintsSQL = [
            "ALTER TABLE `report_responses` ADD CONSTRAINT `fk_report_responses_report_id` FOREIGN KEY (`report_id`) REFERENCES `reports` (`id`) ON DELETE CASCADE",
            "ALTER TABLE `report_responses` ADD CONSTRAINT `fk_report_responses_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE"
        ];
        
        foreach ($addConstraintsSQL as $index => $constraintSQL) {
            try {
                logInfo("Attempting to add foreign key constraint", ['constraint_index' => $index]);
                $constraintResult = $conn->query($constraintSQL);
                if ($constraintResult) {
                    logInfo("Foreign key constraint added successfully", ['constraint_index' => $index]);
                } else {
                    logInfo("Foreign key constraint already exists or failed to add", [
                        'constraint_index' => $index,
                        'error' => $conn->error,
                        'errno' => $conn->errno
                    ]);
                }
            } catch (Exception $e) {
                logInfo("Foreign key constraint exception (likely already exists)", [
                    'constraint_index' => $index,
                    'error' => $e->getMessage()
                ]);
            }
        }
    }
    
} catch (Exception $e) {
    logError("Exception during table creation", [
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
    echo json_encode(['success' => false, 'message' => 'Database setup error. Please contact administrator.']);
    exit;
}

// Handle file upload if present
$attachmentPath = null;
if (isset($_FILES['response_attachment']) && $_FILES['response_attachment']['error'] === UPLOAD_ERR_OK) {
    logInfo("File upload detected for response", [
        'file_name' => $_FILES['response_attachment']['name'],
        'file_size' => $_FILES['response_attachment']['size'],
        'file_type' => $_FILES['response_attachment']['type']
    ]);
    
    $uploadDir = '../../uploads/reports/responses/';
    
    // Create directory if it doesn't exist
    if (!file_exists($uploadDir)) {
        logInfo("Creating upload directory", ['directory' => $uploadDir]);
        if (!mkdir($uploadDir, 0777, true)) {
            logError("Failed to create upload directory", ['directory' => $uploadDir]);
            echo json_encode(['success' => false, 'message' => 'Failed to create upload directory']);
            exit;
        }
    }
    
    // Validate file type and size
    $allowedTypes = ['pdf', 'doc', 'docx', 'txt', 'jpg', 'jpeg', 'png'];
    $fileExtension = strtolower(pathinfo($_FILES['response_attachment']['name'], PATHINFO_EXTENSION));
    $maxFileSize = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($fileExtension, $allowedTypes)) {
        logError("Invalid file type for response attachment", [
            'file_extension' => $fileExtension,
            'allowed_types' => $allowedTypes
        ]);
        echo json_encode(['success' => false, 'message' => 'Invalid file type. Allowed: ' . implode(', ', $allowedTypes)]);
        exit;
    }
    
    if ($_FILES['response_attachment']['size'] > $maxFileSize) {
        logError("File too large for response attachment", [
            'file_size' => $_FILES['response_attachment']['size'],
            'max_size' => $maxFileSize
        ]);
        echo json_encode(['success' => false, 'message' => 'File too large. Maximum size: 5MB']);
        exit;
    }
    
    $fileName = time() . '_' . uniqid() . '.' . $fileExtension;
    $uploadPath = $uploadDir . $fileName;
    
    if (move_uploaded_file($_FILES['response_attachment']['tmp_name'], $uploadPath)) {
        $attachmentPath = $fileName;
        logInfo("File uploaded successfully for response", [
            'original_name' => $_FILES['response_attachment']['name'],
            'saved_name' => $fileName
        ]);
    } else {
        logError("Failed to move uploaded file", [
            'temp_name' => $_FILES['response_attachment']['tmp_name'],
            'target_path' => $uploadPath
        ]);
        echo json_encode(['success' => false, 'message' => 'Failed to upload attachment']);
        exit;
    }
}

// Final check: Verify table exists before attempting insert
$finalTableCheck = $conn->query("SHOW TABLES LIKE 'report_responses'");
$tableExistsFinal = $finalTableCheck && $finalTableCheck->num_rows > 0;

logInfo("Final table existence check before insert", [
    'table_exists' => $tableExistsFinal,
    'about_to_insert' => true,
    'report_id' => $reportId,
    'user_id' => $userId
]);

if (!$tableExistsFinal) {
    logError("Table still does not exist after creation attempts", [
        'report_id' => $reportId,
        'user_id' => $userId
    ]);
    echo json_encode(['success' => false, 'message' => 'Database table setup failed. Please contact administrator.']);
    exit;
}

try {
    // Insert the response
    $sql = "INSERT INTO report_responses (report_id, user_id, response_text, attachment, created_at) 
            VALUES (?, ?, ?, ?, NOW())";
    
    logInfo("Preparing response insert statement", [
        'sql' => $sql,
        'report_id' => $reportId,
        'user_id' => $userId,
        'has_attachment' => !empty($attachmentPath)
    ]);
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $stmt->bind_param("iiss", $reportId, $userId, $responseText, $attachmentPath);
    
    logInfo("Executing response insert statement", [
        'report_id' => $reportId,
        'user_id' => $userId,
        'response_length' => strlen($responseText)
    ]);
    
    if ($stmt->execute()) {
        $responseId = $stmt->insert_id;
        
        logInfo("Report response submitted successfully", [
            'user_id' => $userId,
            'report_id' => $reportId,
            'response_id' => $responseId,
            'has_attachment' => !empty($attachmentPath)
        ]);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Response submitted successfully',
            'response_id' => $responseId
        ]);
    } else {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    logError("Failed to submit report response", [
        'user_id' => $userId,
        'report_id' => $reportId,
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'sql_error' => $conn->error ?? 'none',
        'sql_errno' => $conn->errno ?? 'none'
    ]);
    
    echo json_encode(['success' => false, 'message' => 'Failed to submit response. Please try again.']);
}

$conn->close();
logInfo("Response submission process completed", ['user_id' => $userId, 'report_id' => $reportId]);
?>
