<?php
declare(strict_types=1);

require __DIR__ . '/../lib/helpers.php';
require __DIR__ . '/../lib/security.php';

$app = require __DIR__ . '/../config/app.php';
$db  = require __DIR__ . '/../config/db.php';

$errors = [];
$okMsg  = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check($_POST['csrf'] ?? '');

    $title   = trim($_POST['title'] ?? '');
    $docType = trim($_POST['doc_type'] ?? '');
    $file    = $_FILES['file'] ?? null;

    if (!$file || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        $errors[] = 'Please choose a file to upload.';
    } else {
        if ($file['size'] > $app['max_upload_bytes']) $errors[] = 'File too large.';
        $mime = detect_mime($file['tmp_name']);
        if (!in_array($mime, $app['allowed_mimes'], true)) $errors[] = "File type not allowed ($mime).";
    }

    if (!$errors) {
        ensure_storage($app['storage_dir']);

        $origName  = $file['name'];
        $ext       = safe_ext($origName);
        $basename  = random_basename();
        $storedRel = date('Y/m/d') . '/' . $basename . ($ext ? ".$ext" : '');
        $storedAbs = rtrim($app['storage_dir'], '/') . '/' . $storedRel;

        if (!is_dir(dirname($storedAbs))) mkdir(dirname($storedAbs), 0775, true);

        if (!move_uploaded_file($file['tmp_name'], $storedAbs)) {
            $errors[] = 'Failed to save file.';
        } else {
            $stmt = $db->prepare("
              INSERT INTO documents (filename, filepath, title, doc_type, filesize, owner_user_id, current_version_id, status, created_by)
              VALUES (:filename, :filepath, :title, :doc_type, :filesize, :owner_user_id, NULL, 'active', :created_by)
            ");
            $stmt->execute([
                ':filename'       => $origName,
                ':filepath'       => $storedRel,
                ':title'          => $title ?: pathinfo($origName, PATHINFO_FILENAME),
                ':doc_type'       => $docType ?: null,
                ':filesize'       => (int)($file['size'] ?? 0),
                ':owner_user_id'  => $app['current_user_id'],
                ':created_by'     => $app['current_user_id'],
            ]);
            $okMsg = 'File uploaded successfully.';
        }
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?=h($app['app_name'])?> · Upload</title>
  <link rel="stylesheet" href="assets/bootstrap.min.css">
  <style>body{padding:20px}</style>
</head>
<body>
  <div class="container">
    <h1 class="mb-4">Upload Document</h1>

    <?php if ($okMsg): ?>
      <div class="alert alert-success"><?=h($okMsg)?></div>
      <p><a class="btn btn-primary" href="<?=h(base_url('index.php'))?>">Back to list</a></p>
    <?php endif; ?>

    <?php if ($errors): ?>
      <div class="alert alert-danger">
        <ul class="mb-0"><?php foreach ($errors as $e): ?><li><?=h($e)?></li><?php endforeach; ?></ul>
      </div>
    <?php endif; ?>

    <form action="" method="post" enctype="multipart/form-data" class="card p-3">
      <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
      <div class="mb-3">
        <label class="form-label">Title (optional)</label>
        <input type="text" name="title" class="form-control" maxlength="512">
      </div>
      <div class="mb-3">
        <label class="form-label">Document Type (optional)</label>
        <input type="text" name="doc_type" class="form-control" maxlength="120" placeholder="e.g., Invoice, Contract, Survey Plan">
      </div>
      <div class="mb-3">
        <label class="form-label">File</label>
        <input type="file" name="file" class="form-control" required>
        <div class="form-text">Max <?=h(number_format($app['max_upload_bytes']/1048576))?> MB. Allowed: PDF, images, DOC/DOCX, XLS/XLSX, ZIP, TXT.</div>
      </div>
      <div>
        <button class="btn btn-success">Upload</button>
        <a class="btn btn-secondary" href="<?=h(base_url('index.php'))?>">Cancel</a>
      </div>
    </form>
  </div>
</body>
</html>
