<?php
// db/staff-upload-photo.php
header('Content-Type: application/json');
require_once '../core/api.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') exit(json_encode(['success'=>false]));

$id = $_POST['staff_id'] ?? null;
if (!$id || empty($_FILES['photo'])) exit(json_encode(['success'=>false, 'message'=>'Faltan datos']));

$dir = '../uploads/staff/';
if (!is_dir($dir)) mkdir($dir, 0777, true);

$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$name = 'staff_'.$id.'_'.time().'.'.$ext;
$target = $dir.$name;

// Mover imagen y actualizar BD
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
    $publicPath = 'uploads/staff/' . $name;
    $stmt = $pdo->prepare("UPDATE staff SET profile_photo_url = ? WHERE id = ?");
    $stmt->execute([$publicPath, $id]);
    echo json_encode(['success' => true, 'path' => $publicPath]);
} else {
    echo json_encode(['success' => false, 'message' => 'Error al guardar archivo']);
}
?>