| Current Path : /var/www/cesa.co.za/cceadmin/ |
| Current File : /var/www/cesa.co.za/cceadmin/CCEWeeklySessionsImport.php |
<?php
/**
* CCE Weekly Sessions Import.
* Step 1: Upload Excel → Step 2: Confirm list → Step 3: Save to DB.
*/
session_start();
// PHPMaker environment for header/footer and menu
$cceadminDir = __DIR__;
if (is_file($cceadminDir . '/ewcfg7.php')) {
include_once $cceadminDir . '/ewcfg7.php';
include_once $cceadminDir . '/ewmysql7.php';
include_once $cceadminDir . '/phpfn7.php';
include_once $cceadminDir . '/CCEWeeklySessionsinfo.php';
include_once $cceadminDir . '/CCEUsersinfo.php';
include_once $cceadminDir . '/userfn7.php';
}
$gsExport = '';
// Globals required by cAdvancedSecurity->ValidateUser() / AutoLogin
$Language = new cLanguage();
$GLOBALS['Language'] = $Language;
$GLOBALS["CCEWeeklySessions"] = new cCCEWeeklySessions();
$GLOBALS['CCEUsers'] = new cCCEUsers();
$conn = ew_Connect();
$Security = new cAdvancedSecurity();
$Security->AutoLogin();
$GLOBALS['Security'] = $Security;
if (!$Security->IsLoggedIn()) {
$Security->SaveLastUrl();
header('Location: login.php');
exit;
}
$step = isset($_POST['step']) ? $_POST['step'] : (isset($_GET['step']) ? $_GET['step'] : 'upload');
$message = '';
$error = '';
$importErrors = array(); // detailed errors to show user
$parsed = array();
$year = isset($_POST['year']) ? (int) $_POST['year'] : (isset($_GET['year']) ? (int) $_GET['year'] : (int) date('Y'));
// Handle confirmation and save
if ($step === 'confirm' && isset($_POST['confirm']) && $_POST['confirm'] === '1') {
$stored = isset($_SESSION['cce_import_sessions']) ? $_SESSION['cce_import_sessions'] : null;
$scheduleId = isset($_POST['ScheduleID']) ? (int) $_POST['ScheduleID'] : null;
if (!$stored || !is_array($stored) || count($stored) === 0) {
$error = 'No session data to import. Please upload the file again.';
$step = 'upload';
} elseif (!$scheduleId) {
$error = 'Please select a schedule.';
$step = 'preview';
$parsed = $stored;
} else {
global $sqlf;
$setup = new CCESetup($sqlf);
$setupRow = $setup->getSetup();
$inserted = 0;
$skipped = 0;
$fail = 0;
$importErrors = array();
foreach ($stored as $idx => $row) {
$sessionDate = $row['SessionDate'];
$startTime = $row['StartTime'] ?? null;
if ($startTime === '') {
$startTime = null;
}
$subDate = $row['SubmissionDate'] ?? null;
if ($subDate === '' || $subDate === null) {
$subDate = null;
}
$endTime = $row['EndTime'] ?? null;
if ($endTime === '') {
$endTime = null;
}
// Skip if this session already exists (same schedule + date + start time)
$startCond = ($startTime !== null && $startTime !== '')
? "StartTime = " . $sqlf->qstr($startTime)
: "StartTime IS NULL";
$existing = $sqlf->getRow(
"SELECT CCEWeeklySessionID FROM CCEWeeklySessions WHERE ScheduleID = " . (int) $scheduleId .
" AND SessionDate = " . $sqlf->qstr($sessionDate) . " AND " . $startCond . " LIMIT 1"
);
if ($existing && !empty($existing['CCEWeeklySessionID'])) {
$skipped++;
continue;
}
// Build record; omit date/time keys when null so INSERT uses SQL NULL (autoExecute turns null into '' which MySQL rejects for DATE/TIME)
$record = array(
'ScheduleID' => $scheduleId,
'SessionDate' => $sessionDate,
'Description' => $row['Description'] ?? null,
'PresentationRef' => $row['LectureReference'] ?? null,
'AssignmentRef' => $row['Assignment'] ?? null,
'PresenterName' => $row['Presenter'] ?? null,
'Duration' => $row['SessionBackup'] ?? null,
);
if ($startTime !== null && $startTime !== '') {
$record['StartTime'] = $startTime;
}
if ($endTime !== null && $endTime !== '') {
$record['EndTime'] = $endTime;
}
if ($subDate !== null && $subDate !== '') {
$record['AssignmentSubDate'] = $subDate;
}
try {
$sqlf->autoExecute('CCEWeeklySessions', $record, 'INSERT', null, '');
$inserted++;
} catch (Exception $e) {
$fail++;
$importErrors[] = 'Row ' . ($idx + 1) . ' (' . ($row['SessionDate'] ?? '') . ' ' . ($row['StartTime'] ?? '') . '): ' . $e->getMessage();
}
}
unset($_SESSION['cce_import_sessions']);
$message = "Import complete. {$inserted} session(s) saved.";
if ($skipped > 0) {
$message .= " {$skipped} skipped (already exist).";
}
if ($fail > 0) {
$message .= " {$fail} row(s) failed.";
}
$step = 'upload';
}
}
// Handle file upload and parse
if ($step === 'upload' && !empty($_FILES['excel_file']['tmp_name']) && is_uploaded_file($_FILES['excel_file']['tmp_name'])) {
$originalName = isset($_FILES['excel_file']['name']) ? $_FILES['excel_file']['name'] : null;
$parser = new WeeklySessionsParser($year);
$result = $parser->parseFile($_FILES['excel_file']['tmp_name'], $originalName);
if (!empty($result['errors'])) {
$error = 'Upload/parse failed.';
$importErrors = $result['errors'];
$step = 'upload';
} elseif (empty($result['rows'])) {
$error = 'No session rows found in the spreadsheet. Check column order: DATE, START TIME, LECTURE REFERENCE, DESCRIPTION, PRESENTER, SESSION BACKUP, ASSIGNMENT, SUBMISSION DATE.';
$step = 'upload';
} else {
$_SESSION['cce_import_sessions'] = $result['rows'];
$parsed = $result['rows'];
$step = 'preview';
}
}
// Build schedule options for confirmation step
$scheduleOptions = array();
$currentScheduleId = null;
if (in_array($step, array('preview', 'confirm'), true)) {
global $sqlf;
$setup = new CCESetup($sqlf);
$setupRow = $setup->getSetup();
$currentScheduleId = $setupRow ? (int) $setupRow['CurrentScheduleID'] : null;
try {
$rows = $sqlf->getAll("SELECT ScheduleID, ScheduleName FROM CCESchedules ORDER BY ScheduleID DESC");
foreach ($rows as $r) {
$scheduleOptions[(int) $r['ScheduleID']] = $r['ScheduleName'] ?? 'Schedule ' . $r['ScheduleID'];
}
} catch (Exception $e) {
$rows = array();
}
if (empty($scheduleOptions) && $currentScheduleId) {
$scheduleOptions[$currentScheduleId] = 'Current schedule (' . $currentScheduleId . ')';
}
}
?>
<?php include (is_file(__DIR__ . '/header.php') ? __DIR__ . '/header.php' : 'header.php'); ?>
<style>
.cce-import-container { max-width: 1000px; margin: 0 auto; padding: 16px; }
.cce-import-container h1 { margin-top: 0; color: #333; }
.cce-import-container .msg { padding: 10px; margin: 10px 0; border-radius: 4px; }
.cce-import-container .msg.error { background: #ffebee; color: #c62828; }
.cce-import-container .msg.success { background: #e8f5e9; color: #2e7d32; }
.cce-import-container .import-errors { margin-top: 8px; padding: 10px; background: #fff3e0; border-left: 4px solid #e65100; font-size: 13px; max-height: 300px; overflow-y: auto; }
.cce-import-container .import-errors ul { margin: 0; padding-left: 20px; }
.cce-import-container label { display: block; margin-bottom: 4px; font-weight: bold; }
.cce-import-container input[type="file"], .cce-import-container input[type="number"], .cce-import-container select { margin-bottom: 12px; padding: 6px 10px; }
.cce-import-container button, .cce-import-container .btn { display: inline-block; padding: 8px 16px; background: #1565c0; color: #fff; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; font-size: 14px; }
.cce-import-container button:hover, .cce-import-container .btn:hover { background: #0d47a1; }
.cce-import-container .btn.secondary { background: #757575; }
.cce-import-container .btn.secondary:hover { background: #616161; }
.cce-import-container table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 13px; }
.cce-import-container th, .cce-import-container td { border: 1px solid #ddd; padding: 8px; text-align: left; }
.cce-import-container th { background: #e3f2fd; }
.cce-import-container tr:nth-child(even) { background: #fafafa; }
.cce-import-container .preview-actions { margin-top: 16px; }
.cce-import-container .preview-actions form { display: inline-block; margin-right: 8px; }
.cce-import-container .back-link { margin-bottom: 16px; }
</style>
<div class="cce-import-container">
<div class="back-link">
<a href="CCEWeeklySessionslist.php" class="btn secondary">← Back to Weekly Sessions list</a>
</div>
<h1>CCE Weekly Sessions Import</h1>
<?php if ($message): ?>
<div class="msg success"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="msg error"><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>
<?php if (!empty($importErrors)): ?>
<div class="import-errors">
<strong>Import errors:</strong>
<ul>
<?php foreach ($importErrors as $err): ?>
<li><?php echo htmlspecialchars($err); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($step === 'upload'): ?>
<p>Upload an Excel spreadsheet (.xlsx or .xls) with columns: <strong>DATE</strong>, <strong>START TIME</strong>, <strong>LECTURE REFERENCE</strong>, <strong>DESCRIPTION</strong>, <strong>PRESENTER</strong>, <strong>SESSION BACKUP</strong>, <strong>ASSIGNMENT</strong>, <strong>SUBMISSION DATE</strong>. The date in the first column applies to following rows until a new date is given.</p>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="step" value="upload">
<label>Year for dates (e.g. 26-May → May 26, this year)</label>
<input type="number" name="year" value="<?php echo (int) $year; ?>" min="2020" max="2030">
<label>Excel file</label>
<input type="file" name="excel_file" accept=".xlsx,.xls" required>
<br><br>
<button type="submit">Upload and preview</button>
</form>
<?php endif; ?>
<?php if ($step === 'preview' && count($parsed) > 0): ?>
<p><strong><?php echo count($parsed); ?></strong> session(s) will be imported. Review below and choose the schedule, then confirm.</p>
<?php if (empty($scheduleOptions)): ?>
<div class="msg error">No schedule found. Ensure CCESetup has CurrentScheduleID set or that table CCESchedules exists.</div>
<?php else: ?>
<form method="post" id="schedule-form">
<input type="hidden" name="step" value="confirm">
<input type="hidden" name="confirm" value="1">
<label>Import into schedule</label>
<select name="ScheduleID" required>
<?php foreach ($scheduleOptions as $id => $name): ?>
<option value="<?php echo (int) $id; ?>" <?php echo (isset($currentScheduleId) && $currentScheduleId === $id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($name); ?></option>
<?php endforeach; ?>
</select>
</form>
<?php endif; ?>
<div style="overflow-x: auto;">
<table>
<thead>
<tr>
<th>Date</th>
<th>Start time</th>
<th>End time</th>
<th>Lecture ref</th>
<th>Description</th>
<th>Presenter</th>
<th>Backup</th>
<th>Assignment</th>
<th>Submission</th>
</tr>
</thead>
<tbody>
<?php foreach ($parsed as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['SessionDate'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['StartTime'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['EndTime'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['LectureReference'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['Description'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['Presenter'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['SessionBackup'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['Assignment'] ?? ''); ?></td>
<td><?php echo htmlspecialchars($r['SubmissionDate'] ?? $r['SubmissionDateDesc'] ?? ''); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="preview-actions">
<?php if (!empty($scheduleOptions)): ?>
<button type="submit" form="schedule-form">Confirm and import</button>
<?php endif; ?>
<a href="CCEWeeklySessionsImport.php" class="btn secondary"><?php echo empty($scheduleOptions) ? 'Back' : 'Cancel'; ?></a>
</div>
<?php endif; ?>
</div>
<?php include (is_file(__DIR__ . '/footer.php') ? __DIR__ . '/footer.php' : 'footer.php'); ?>