<?php
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();
require_once __DIR__ . '/config.php';

$eqp_id = (int)($_POST['equipment_id'] ?? 0);
if (!$eqp_id) { http_response_code(400); exit('ID inválido'); }

$dir = __DIR__ . '/uploads/equipment';
if (!is_dir($dir)) { @mkdir($dir, 0775, true); }

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
  exit('Falha no upload');
}

$size = $_FILES['file']['size'];
$type = mime_content_type($_FILES['file']['tmp_name']);
$name = $_FILES['file']['name'];

$allowed = ['image/png','image/jpeg'];
if (!in_array($type, $allowed, true)) { exit('Tipo inválido (use PNG/JPG)'); }
if ($size > 8*1024*1024) { exit('Arquivo muito grande (max 8MB)'); }

$ext = pathinfo($name, PATHINFO_EXTENSION) ?: 'jpg';
$dest = $dir . '/' . $eqp_id . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) { exit('Erro ao salvar arquivo'); }

$pdo->prepare('UPDATE equipment SET foto_path=? WHERE id=?')->execute([basename($dest), $eqp_id]);
$pdo->prepare("INSERT INTO equipment_log (equipment_id,user_id,action,notes) VALUES (?,?,?,?)")
    ->execute([$eqp_id, current_user()['id'], 'PHOTO_UPLOADED', 'Foto: '.basename($dest)]);

header('Location: ' . base_url('equipment.php'));
