<?php
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

if ($_SESSION['user_role'] !== 'personnel') {
    header('Location: ../dashboard.php');
    exit;
}

$fiche_id = filter_input(INPUT_GET, 'fiche_id', FILTER_VALIDATE_INT);
if (!$fiche_id) {
    header('Location: index.php');
    exit;
}

$pdo = getPDO();
$stmt = $pdo->prepare("SELECT id, createur_id, sous_dossier_id FROM fiches WHERE id = ? AND deleted_at IS NULL");
$stmt->execute([$fiche_id]);
$fiche = $stmt->fetch();
if (!$fiche) {
    $_SESSION['error'] = "Fiche introuvable.";
    header('Location: index.php');
    exit;
}
if ($_SESSION['user_id'] != $fiche['createur_id']) {
    $_SESSION['error'] = "Vous n'avez pas les droits.";
    header("Location: sous_dossier.php?id=" . $fiche['sous_dossier_id']);
    exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fichier'])) {
    $file = $_FILES['fichier'];
    $allowed = ['application/pdf','image/jpeg','image/png'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error = "Erreur upload.";
    } elseif (!in_array($file['type'], $allowed)) {
        $error = "Type non autorisé (PDF, JPG, PNG).";
    } elseif ($file['size'] > 5*1024*1024) {
        $error = "Fichier trop gros (max 5 Mo).";
    } else {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $name = 'fiche_' . $fiche_id . '_' . time() . '.' . $ext;
        $dir = '../uploads/fiches/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $path = $dir . $name;
        if (move_uploaded_file($file['tmp_name'], $path)) {
            $stmt = $pdo->prepare("SELECT pdf_path FROM fiches WHERE id = ?");
            $stmt->execute([$fiche_id]);
            $old = $stmt->fetchColumn();
            if ($old && file_exists($old)) unlink($old);
            $stmt = $pdo->prepare("UPDATE fiches SET pdf_path = ? WHERE id = ?");
            $stmt->execute([$path, $fiche_id]);
            logAction($pdo, $_SESSION['user_id'], 'upload_fichier', "Fiche $fiche_id");
            $_SESSION['success'] = "Fichier attaché.";
            header("Location: fiche_view.php?id=$fiche_id");
            exit;
        } else {
            $error = "Erreur sauvegarde.";
        }
    }
}

require_once '../includes/header.php';
?>
<div class="row justify-content-center"><div class="col-md-6"><div class="card"><div class="card-header bg-primary text-white"><h5><i class="fas fa-paperclip"></i> Attacher un fichier</h5></div><div class="card-body"><?php if($error):?><div class="alert alert-danger"><?=$error?></div><?php endif;?><form method="post" enctype="multipart/form-data"><div class="mb-3"><label>Fichier (PDF, JPG, PNG, max 5 Mo)</label><input type="file" name="fichier" class="form-control" required accept=".pdf,.jpg,.jpeg,.png"></div><button type="submit" class="btn btn-primary">Uploader</button><a href="fiche_view.php?id=<?=$fiche_id?>" class="btn btn-secondary">Annuler</a></form></div></div></div></div>
<?php require_once '../includes/footer.php'; ?>