<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_documentation_schema();
require_permission('uploads.manage', ['super_admin','clinic_admin']);
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
$branches = branch_options();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            throw new RuntimeException('Choose a file to upload.');
        }

        $title = trim((string) ($_POST['title'] ?? ''));
        $category = trim((string) ($_POST['category'] ?? 'Other'));
        $description = trim((string) ($_POST['description'] ?? ''));
        $branchId = (int) ($_POST['branch_id'] ?? 0);
        if ($title === '') throw new RuntimeException('Enter a file title.');

        $file = $_FILES['file'];
        if ((int) $file['size'] <= 0 || (int) $file['size'] > 25 * 1024 * 1024) {
            throw new RuntimeException('Files must be between 1 byte and 25 MB.');
        }

        $allowed = [
            'application/pdf' => 'pdf',
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
            'text/plain' => 'txt',
            'text/csv' => 'csv',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
        ];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = (string) $finfo->file((string) $file['tmp_name']);
        if (!isset($allowed[$mime])) {
            throw new RuntimeException('Allowed files: PDF, JPG, PNG, WEBP, TXT, CSV, DOCX, XLSX, and PPTX.');
        }

        $stored = bin2hex(random_bytes(24)) . '.' . $allowed[$mime];
        $target = private_system_upload_directory() . '/' . $stored;
        if (!move_uploaded_file((string) $file['tmp_name'], $target)) {
            throw new RuntimeException('The file could not be stored. Check the private storage permissions.');
        }
        @chmod($target, 0640);

        $stmt = $pdo->prepare(
            'INSERT INTO `' . table('system_uploads') . '` '
            . '(branch_id,category,title,file_name,stored_name,mime_type,file_size,description,uploaded_by,created_at) '
            . 'VALUES (?,?,?,?,?,?,?,?,?,NOW())'
        );
        $stmt->execute([
            $branchId > 0 ? $branchId : null,
            $category,
            $title,
            basename((string) $file['name']),
            $stored,
            $mime,
            (int) $file['size'],
            $description !== '' ? $description : null,
            (int) current_user()['id'],
        ]);
        $id = (int) $pdo->lastInsertId();
        audit('system_file_uploaded', 'system_upload', $id, ['title'=>$title,'category'=>$category,'mime'=>$mime]);
        flash('success', 'File uploaded securely.');
        header('Location: uploads.php');
        exit;
    } catch (Throwable $exception) {
        $error = $exception->getMessage();
    }
}

$rows = $pdo->query(
    'SELECT f.*,b.name branch_name,u.name uploader '
    . 'FROM `' . table('system_uploads') . '` f '
    . 'LEFT JOIN `' . table('branches') . '` b ON b.id=f.branch_id '
    . 'LEFT JOIN `' . table('users') . '` u ON u.id=f.uploaded_by '
    . 'ORDER BY f.created_at DESC LIMIT 200'
)->fetchAll();

render_header('Files & Uploads');
?>
<?php if ($error): ?><div class="flash error"><?= e($error) ?></div><?php endif; ?>
<section class="stats compact-stats">
    <?php stat_card('Protected files', count($rows), 'Stored outside the public web root'); ?>
    <?php stat_card('Maximum file size', '25 MB', 'Per upload'); ?>
    <?php stat_card('Access', 'Admin', 'Superuser and authorized administrators'); ?>
    <?php stat_card('Audit', 'Enabled', 'Uploads and downloads are recorded'); ?>
</section>
<div class="toolbar module-toolbar">
    <div><strong>Clinic file center</strong><span class="muted">Upload policies, forms, templates, reference files, and clinic documents. Patient clinical files remain under Images & Documents.</span></div>
    <button class="btn primary" type="button" data-open="upload-form">Upload file</button>
</div>
<section class="card table-wrap">
<table><thead><tr><th>File</th><th>Category</th><th>Branch</th><th>Size</th><th>Uploaded by</th><th>Date</th><th></th></tr></thead><tbody>
<?php foreach ($rows as $row): ?>
<tr>
    <td><strong><?= e((string) $row['title']) ?></strong><small><?= e((string) $row['file_name']) ?></small><?php if ($row['description']): ?><small><?= e((string) $row['description']) ?></small><?php endif; ?></td>
    <td><span class="badge"><?= e((string) $row['category']) ?></span></td>
    <td><?= e((string) ($row['branch_name'] ?: 'All branches')) ?></td>
    <td><?= e(number_format(((int) $row['file_size']) / 1024, 1)) ?> KB</td>
    <td><?= e((string) ($row['uploader'] ?: 'System')) ?></td>
    <td><?= e(date('M j, Y g:i A', strtotime((string) $row['created_at']))) ?></td>
    <td><a href="download_upload.php?id=<?= (int) $row['id'] ?>">Download</a></td>
</tr>
<?php endforeach; ?>
<?php if (!$rows): ?><tr><td colspan="7" class="muted">No clinic files have been uploaded.</td></tr><?php endif; ?>
</tbody></table>
</section>

<dialog id="upload-form" class="wide-dialog"><form method="post" enctype="multipart/form-data" class="form-grid">
    <button type="button" class="dialog-close" data-close>×</button>
    <h2 class="wide">Upload protected clinic file</h2>
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <label>Title<input name="title" maxlength="190" required></label>
    <label>Category<select name="category"><option>Policy</option><option>Clinic Form</option><option>Template</option><option>Reference</option><option>Training</option><option>Supplier Document</option><option>Other</option></select></label>
    <label>Branch<select name="branch_id"><option value="">All branches</option><?php foreach ($branches as $branch): ?><option value="<?= (int) $branch['id'] ?>"><?= e((string) $branch['name']) ?></option><?php endforeach; ?></select></label>
    <label>File<input type="file" name="file" accept=".pdf,.jpg,.jpeg,.png,.webp,.txt,.csv,.docx,.xlsx,.pptx" required><small>Maximum 25 MB.</small></label>
    <label class="wide">Description<textarea name="description"></textarea></label>
    <div class="wide"><button class="btn primary" type="submit">Upload securely</button></div>
</form></dialog>
<?php render_footer();
