<?php
/**
 * OT Taskforce — File Upload Handler
 */
require_once __DIR__ . '/../../config/auth.php';
$user = requireLogin();
validateCsrf();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['file'])) {
    header('Location: ../../dashboard.php?page=overtime-taskforce');
    exit;
}

$file = $_FILES['file'];
$description = trim($_POST['description'] ?? '');

// Validate
if ($file['error'] !== UPLOAD_ERR_OK) {
    header('Location: ../../dashboard.php?page=overtime-taskforce&error=upload_failed');
    exit;
}

if ($file['size'] > PORTAL_UPLOAD_MAX) {
    header('Location: ../../dashboard.php?page=overtime-taskforce&error=file_too_large');
    exit;
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mimeType, ALLOWED_DOC_TYPES)) {
    header('Location: ../../dashboard.php?page=overtime-taskforce&error=invalid_type');
    exit;
}

// Check for dangerous extensions
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$dangerousExts = ['php', 'phtml', 'php3', 'php4', 'php5', 'phps', 'pht', 'sh', 'exe', 'bat', 'cmd'];
if (in_array($ext, $dangerousExts)) {
    header('Location: ../../dashboard.php?page=overtime-taskforce&error=dangerous_file');
    exit;
}

// Generate safe filename
$safeName = bin2hex(random_bytes(16)) . '.' . $ext;
$uploadDir = PORTAL_UPLOAD_DIR . '/overtime';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$destPath = $uploadDir . '/' . $safeName;
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    header('Location: ../../dashboard.php?page=overtime-taskforce&error=save_failed');
    exit;
}

// Record in DB
$db = getDB();
$stmt = $db->prepare("INSERT INTO uploads (user_id, filename, original_name, file_type, file_size, module, description) VALUES (:uid, :fn, :on, :ft, :fs, :mod, :desc)");
$stmt->execute([
    ':uid'  => $user['id'],
    ':fn'   => $safeName,
    ':on'   => $file['name'],
    ':ft'   => $mimeType,
    ':fs'   => $file['size'],
    ':mod'  => 'overtime',
    ':desc' => $description,
]);

auditLog('file_upload', $user['id'], "Uploaded: {$file['name']} to overtime module");

header('Location: ../../dashboard.php?page=overtime-taskforce');
exit;
