<?php
require_once 'includes/auth.php';
require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$fiche_id = filter_input(INPUT_POST, 'fiche_id', FILTER_VALIDATE_INT);
$dest = trim($_POST['destinataire'] ?? '');
$sujet = trim($_POST['sujet'] ?? '');
$msg = trim($_POST['message'] ?? '');
if (!$fiche_id || empty($dest) || empty($sujet)) { $_SESSION['error'] = "Paramètres manquants."; header('Location: dashboard.php'); exit; }
$pdo = getPDO();
$stmt = $pdo->prepare("SELECT f.* FROM fiches f WHERE f.id = ?");
$stmt->execute([$fiche_id]);
$fiche = $stmt->fetch();
if (!$fiche) { $_SESSION['error'] = "Fiche introuvable."; header('Location: dashboard.php'); exit; }
$peut_voir = ($_SESSION['user_role'] === 'superadmin' || $_SESSION['user_role'] === 'admin' || $_SESSION['user_id'] == $fiche['createur_id']);
if (!$peut_voir) { $_SESSION['error'] = "Droits insuffisants."; header('Location: dashboard.php'); exit; }
$attachments = [];
if (!empty($_FILES['pj']['name'][0])) {
    $upload_dir = 'uploads/temp/';
    if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
    foreach ($_FILES['pj']['tmp_name'] as $key => $tmp) {
        if ($_FILES['pj']['error'][$key] == UPLOAD_ERR_OK) {
            $name = basename($_FILES['pj']['name'][$key]);
            $dest = $upload_dir . uniqid() . '_' . $name;
            move_uploaded_file($tmp, $dest);
            $attachments[] = $dest;
        }
    }
}
$mail = new PHPMailer(true);
try {
    // Config SMTP (à adapter)
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'votre.email@gmail.com';
    $mail->Password = 'votre_mdp';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;
    $mail->setFrom('no-reply@ciberci.com', 'CIBER Auto-contrôle');
    $mail->addAddress($dest);
    $mail->Subject = $sujet;
    $mail->Body = $msg . "\n\nFiche : " . $fiche['numero_fiche'];
    if ($fiche['pdf_path'] && file_exists($fiche['pdf_path'])) $mail->addAttachment($fiche['pdf_path']);
    foreach ($attachments as $att) $mail->addAttachment($att);
    $mail->send();
    $_SESSION['success'] = "Email envoyé.";
    foreach ($attachments as $att) unlink($att);
} catch (Exception $e) {
    $_SESSION['error'] = "Erreur envoi : " . $mail->ErrorInfo;
}
header("Location: fiche_view.php?id=$fiche_id");
exit;