<?php
header('Content-Type: application/json');
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

$user = checkSession();
if (!$user || !in_array($user['role'], ['admin', 'programmer', 'board'])) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$id = $data['id'] ?? null;
$status = $data['status'] ?? '';
$observations = $data['observations'] ?? '';
$assigned_to = $data['assignedTo'] ?? null;
$target_id = $data['targetId'] ?? null;

if (!$id || !$status) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

try {
    $pdo = getPDO();
    $stmt = $pdo->prepare("UPDATE payment_reports SET status = ?, observations = ?, assigned_to = ?, target_id = ? WHERE id = ?");
    $stmt->execute([$status, $observations, $assigned_to, $target_id, $id]);
    
    logSystemAction("ACTUALIZÓ estatus de reporte ID: " . $id . " a " . $status, "PAGOS");
    
    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>