getAllDataTypes(); $categories = $data_source_manager->getAllCategories(); $primaryRulesMap = []; foreach ($data_types as $type) { $typeName = $type['dspstds_name_en'] ?? null; $rules = $data_source_manager->getPrimaryFileRulesForType($typeName); $acceptList = []; foreach ($rules['extensions'] ?? [] as $ext) { $acceptList[] = '.' . strtolower($ext); } $primaryRulesMap[$type['pkdspstds_id']] = [ 'accept' => $acceptList, 'description' => $rules['description'] ?? 'CSV, JSON, PDF, XLS, XLSX', ]; } $defaultPrimaryRules = $data_source_manager->getPrimaryFileRulesForType(null); $defaultPrimaryAccept = []; foreach ($defaultPrimaryRules['extensions'] ?? [] as $ext) { $defaultPrimaryAccept[] = '.' . strtolower($ext); } $initialPrimaryDescription = $defaultPrimaryRules['description'] ?? 'CSV, JSON, PDF, XLS, XLSX'; // Handle form submissions if ($_SERVER['REQUEST_METHOD'] === 'POST') { $title_en = trim($_POST['title_en'] ?? ''); $title_kh = trim($_POST['title_kh'] ?? ''); $description = trim($_POST['description'] ?? ''); $type_id = filter_var($_POST['type_id'] ?? '', FILTER_SANITIZE_NUMBER_INT); $category_id = filter_var($_POST['category_id'] ?? '', FILTER_SANITIZE_NUMBER_INT); $public_date = trim($_POST['public_date'] ?? ''); $status = trim($_POST['status'] ?? 'Pending Review'); $selectedDataType = null; if (!empty($type_id)) { $selectedDataType = $data_source_manager->getDataTypeById((int)$type_id); } $current_files = [ 'dspsds_filename' => trim($_POST['current_filename'] ?? ''), 'dspsds_filename1' => trim($_POST['current_filename1'] ?? ''), 'dspsds_filename2' => trim($_POST['current_filename2'] ?? ''), 'dspsds_filename3' => trim($_POST['current_filename3'] ?? ''), ]; $final_files = $current_files; $file_inputs = [ 'dspsds_filename' => 'data_file', 'dspsds_filename1' => 'data_file1', 'dspsds_filename2' => 'data_file2', 'dspsds_filename3' => 'data_file3', ]; $file_labels = [ 'dspsds_filename' => 'Primary Data File', 'dspsds_filename1' => 'Questionnaire / Data Dictionary', 'dspsds_filename2' => 'Protocol / User Guide', 'dspsds_filename3' => 'Other Supporting Document', ]; $remove_files = $_POST['remove_files'] ?? []; if (!is_array($remove_files)) { $remove_files = [$remove_files]; } foreach ($file_inputs as $column => $inputName) { if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] === UPLOAD_ERR_NO_FILE) { continue; } try { if ($_FILES[$inputName]['error'] !== UPLOAD_ERR_OK) { throw new Exception('Upload error code: ' . $_FILES[$inputName]['error']); } $fileRules = null; if ($column === 'dspsds_filename') { $fileRules = $data_source_manager->getPrimaryFileRulesForType($selectedDataType['dspstds_name_en'] ?? null); } $uploadedName = $data_source_manager->handleDataSourceFileUpload($_FILES[$inputName], $fileRules); if ($uploadedName) { if (!empty($current_files[$column]) && $current_files[$column] !== $uploadedName) { $oldPath = $data_source_manager->getUploadDir() . $current_files[$column]; if (is_file($oldPath)) { unlink($oldPath); } } $final_files[$column] = $uploadedName; } } catch (Exception $e) { $friendlyLabel = $file_labels[$column] ?? $inputName; set_message('File upload failed for ' . htmlspecialchars($friendlyLabel) . ': ' . $e->getMessage(), 'danger'); $final_files[$column] = $current_files[$column]; } } foreach ($remove_files as $column) { if (!array_key_exists($column, $final_files)) { continue; } if (!empty($current_files[$column])) { $oldPath = $data_source_manager->getUploadDir() . $current_files[$column]; if (is_file($oldPath)) { unlink($oldPath); } } $final_files[$column] = ''; } // Basic validation for required fields if (empty($title_en) || empty($type_id) || empty($category_id)) { set_message("Title, Data Type, and Category are required.", "danger"); // Redirect to preserve form data or re-display form with errors // For now, we'll just redirect to list, but a better UX would be to stay on the form header("Location: manage_my_datasources.php?action=" . ($action === 'add_submit' ? 'add' : 'edit&id=' . $ds_id)); exit(); } // Determine the public date to pass to the add/update methods // The DataSource class's add/update methods have logic for this, so we'll pass it as a string or null $final_public_date = (!empty($public_date) && $status === 'Active') ? $public_date : null; if ($action === 'add_submit') { try { // Corrected call to addDataSource if ($data_source_manager->addDataSource( $type_id, $category_id, $owner_person_id, // Data owner is the logged-in person $final_files['dspsds_filename'], $title_en, $title_kh, $description, $status, $user_id, // User who registered it (logged-in user) $final_files['dspsds_filename1'], $final_files['dspsds_filename2'], $final_files['dspsds_filename3'] )) { set_message("Data source added successfully!", "success"); } else { set_message("Failed to add data source.", "danger"); } } catch (Exception $e) { set_message("Error adding data source: " . $e->getMessage(), "danger"); } } elseif ($action === 'edit_submit' && $ds_id) { try { // Corrected call to updateDataSource if ($data_source_manager->updateDataSource( $ds_id, $type_id, $category_id, $owner_person_id, // Data owner is the logged-in person $final_files['dspsds_filename'], $title_en, $title_kh, $description, $status, $user_id, // User who modified it (logged-in user) $final_files['dspsds_filename1'], $final_files['dspsds_filename2'], $final_files['dspsds_filename3'] )) { set_message("Data source updated successfully!", "success"); } else { set_message("Failed to update data source.", "danger"); } } catch (Exception $e) { set_message("Error updating data source: " . $e->getMessage(), "danger"); } } // Redirect after POST to prevent form resubmission header("Location: manage_my_datasources.php"); exit(); } // Handle GET actions if ($action === 'edit' && $ds_id) { $datasource_data = $data_source_manager->getDataSourceById($ds_id); // Crucial security check: Ensure the logged-in owner actually owns this data source if (!$datasource_data || $datasource_data['fkisp_id_of'] != $owner_person_id) { set_message("Data source not found or you don't have permission to edit it.", "danger"); header("Location: manage_my_datasources.php"); exit(); } } elseif ($action === 'delete' && $ds_id) { $datasource = $data_source_manager->getDataSourceById($ds_id); // Crucial security check: Ensure the logged-in owner actually owns this data source if ($datasource && $datasource['fkisp_id_of'] == $owner_person_id) { // Delete associated file on the server $fileColumns = ['dspsds_filename', 'dspsds_filename1', 'dspsds_filename2', 'dspsds_filename3']; foreach ($fileColumns as $column) { if (!empty($datasource[$column])) { $filePath = $data_source_manager->getUploadDir() . $datasource[$column]; if (is_file($filePath)) { unlink($filePath); } } } if ($data_source_manager->deleteDataSource($ds_id)) { set_message("Data source deleted successfully!", "success"); } else { set_message("Failed to delete data source.", "danger"); } } else { set_message("Data source not found or you don't have permission to delete it.", "warning"); } header("Location: manage_my_datasources.php"); exit(); } // Fetch data sources for the current owner for display $my_data_sources = $data_source_manager->getDataSources($owner_person_id); $uploadsWebPath = '../uploads/datasources/'; ?>