| Current Path : /home/emeraadmin/public_html/4d695/ |
| Current File : /home/emeraadmin/public_html/4d695/process_upload.php.tar |
home/emeraadmin/public_html/pages/process_upload.php 0000644 00000020542 15167673417 0016756 0 ustar 00 <?php
// process_upload.php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Include necessary files and classes
require_once '../Classes/Database.php';
require_once '../Classes/Schedules.php';
require_once '../Classes/Task.php';
require_once '../Service/ScheduleService.php';
require_once '../Service/TaskService.php';
require_once '../Service/ServiceService.php';
$serviceService = new ServiceService();
// Check if file is uploaded and process it
if ($_FILES && isset($_FILES['csv_file'])) {
$fileTmpPath = $_FILES['csv_file']['tmp_name'];
$fileName = $_FILES['csv_file']['name'];
$fileSize = $_FILES['csv_file']['size'];
$fileType = $_FILES['csv_file']['type'];
// Check if the uploaded file is a CSV file
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if ($fileExtension !== 'csv') {
echo json_encode(array('error' => 'Invalid file format. Please upload a CSV file.'));
exit;
}
// Move uploaded file to a directory (you may need to adjust the destination directory)
$uploadDir = '../uploads/';
$uploadPath = $uploadDir . $fileName;
if (!move_uploaded_file($fileTmpPath, $uploadPath)) {
$errorCode = $_FILES['file']['error'];
$errorMessage = error_get_last();
echo json_encode(array('error' => 'Failed to move uploaded file. Error code: ' . $errorCode . '. ' . $errorMessage));
exit;
}
// CSV file path
$csvFile = $uploadPath;
// Schedule Name is file name and year is current year
$scheduleName = pathinfo($csvFile, PATHINFO_FILENAME);
//get current user id form the post request
$currentUserId = $_POST['current_user_id'];
// Initialize an array to store tasks
$tasks = [];
// Open the CSV file for reading
if (($handle = fopen($csvFile, "r")) !== FALSE) {
// Read headers from the first row (assuming the first row is headers)
$headers = fgetcsv($handle, 1000, ",");
if ($headers === false) {
echo json_encode(array('error' => 'Failed to read headers from the CSV file.'));
exit;
}
// Iterate through each row of data
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Initialize task array
$task = [
'service' => $data[0], // First column as service ID
'region' => $data[1], // Second column as region
'frequency' => !empty($data[2]) ? $data[2] : '3x/week', // Third column as frequency or default to '3x/week'
'dates' => []
];
// Iterate over date headers and add non-empty dates to the 'dates' array
for ($i = 3; $i < count($headers); $i++) {
// Adjust date format if needed
$date = DateTime::createFromFormat('m/d/Y', $headers[$i]);
if ($date !== false) {
$formattedDate = $date->format('Y-m-d'); // Format date as YYYY-MM-DD
$time = isset($data[$i]) ? $data[$i] : ''; // Get time value or empty string if not set
// Replace 'x' with empty string for time if needed
if (!empty($time)) {
if ($time === 'x') {
$time = null; // Convert 'x' to empty string
}
$task['dates'][] = [
'date' => $formattedDate,
'time' => $time
];
}
} else {
echo json_encode(array('error' => 'Failed to parse date: ' . $headers[$i]));
exit;
}
}
// Add the task to the tasks array only if there are dates with times
if (!empty($task['dates'])) {
$tasks[] = $task;
}
}
// Construct final JSON structure
$jsonOutput = [
'scheduleName' => $scheduleName,
'currentUserId' => $currentUserId,
'tasks' => $tasks
];
// Convert JSON to string
$jsonData = json_encode($jsonOutput);
// Proceed with database insertion using $jsonData
$data = json_decode($jsonData, true); // Decode JSON string to associative array
// Extract schedule name and tasks
$scheduleName = isset($data['scheduleName']) ? trim($data['scheduleName']) : '';
$currentUserId = isset($data['currentUserId']) ? trim($data['currentUserId']) : '';
$tasks = isset($data['tasks']) ? $data['tasks'] : [];
$now = date('Y-m-d H:i:s');
try {
// Create a new schedule
$schedule = new Schedules('', $scheduleName, $currentUserId, false, $now, $now);
$scheduleService = new ScheduleService();
$schedule_id = $scheduleService->addScheduleRetuenlastinsertedid($schedule);
// Check if schedule creation was successful
if (!$schedule_id) {
echo json_encode(array('error' => 'Failed to add schedule.'));
exit;
}
// Loop through tasks array and add each task
foreach ($tasks as $taskData) {
$serviceName = isset($taskData['service']) ? trim($taskData['service']) : '';
$region = isset($taskData['region']) ? trim($taskData['region']) : '';
$frequency = isset($taskData['frequency']) ? trim($taskData['frequency']) : '';
$dates = isset($taskData['dates']) ? $taskData['dates'] : [];
// Validate and format dates and times
$formattedDates = [];
foreach ($dates as $date) {
// Ensure time is converted to empty string if 'x' is found
$time = $date['time'] === 'x' ? null : $date['time'];
$formattedDates[] = [
'date' => $date['date'],
'time' => $time
];
}
// Get service ID from service name and region
$service = $serviceService->getServiceByNameAndRegion($serviceName, $region);
// Check if service exists
if (!$service) {
// Service does not exist, create a new service
$service = new Service("", $serviceName, $region, "", "", "", "", "", "", "Australia", "", "", "", "", $now, $now);
// Attempt to add the service
$service_id = $serviceService->addServicereturnlastid($service);
if (!$service_id) {
// Handle error if service creation fails
echo "Failed to create or retrieve service.";
exit; // Exit or return depending on your flow
}
} else {
// Service already exists, use its ID
$service_id = $service->id;
}
// Create a new task instance with the formatted dates and times
$task = new Task('', $schedule_id, $service_id, $frequency, json_encode($formattedDates), $currentUserId, $currentUserId, $now, $now, false, null, false, false, false, null, null, false);
$taskService = new TaskService();
$task_id = $taskService->addTask($task);
// Check if task creation was successful
if (!$task_id) {
echo json_encode(array('error' => 'Failed to add task.'));
exit;
}
}
// If everything is successful, return a success response
echo json_encode(array('success' => true, 'message' => 'Tasks added successfully.', 'schedule_id' => $schedule_id));
} catch (Exception $e) {
// Handle any exceptions and return an error response
echo json_encode(array('error' => $e->getMessage()));
}
} else {
echo json_encode(array('error' => 'Failed to open the CSV file.'));
}
// Close the file handle
fclose($handle);
} else {
echo json_encode(array('error' => 'No file uploaded or invalid file upload.'));
}
?>