<?php 
require_once '../../config.php';

if (!$_settings->is_logged_in()) {
    exit;
}

$project_id = (int)($_POST['project_id'] ?? 0);
$action     = $_POST['action'] ?? '';
$role       = $_settings->userdata('role');

switch ($action) {

    /* =========================
       FLUJO PMO EXISTENTE
       ========================= */

    case 'send_po':
        $_settings->require_permission('projects','editar');
        $conn->query("
            UPDATE projects
            SET approval_status = 1,
                approval_updated_at = NOW()
            WHERE id = $project_id
        ");
        $_settings->audit('projects','send_po',"Proyecto $project_id enviado a PO");
        break;

    case 'approve_po':
        if ($role !== 'PO') exit;
        $conn->query("
            UPDATE projects
            SET approval_status = 3,
                approval_updated_at = NOW()
            WHERE id = $project_id
        ");
        $_settings->audit('projects','approve_po',"PO aprob¨® proyecto $project_id");
        break;

    case 'observe_po':
        if ($role !== 'PO') exit;
        $conn->query("
            UPDATE projects
            SET approval_status = 2,
                approval_updated_at = NOW()
            WHERE id = $project_id
        ");
        $_settings->audit('projects','observe_po',"PO observ¨® proyecto $project_id");
        break;

    case 'approve_supervisor':
        if ($role !== 'SUPERVISOR') exit;
        $conn->query("
            UPDATE projects
            SET approval_status = 5,
                approval_updated_at = NOW()
            WHERE id = $project_id
        ");
        $_settings->audit('projects','approved',"Supervisor aprob¨® proyecto $project_id");
        break;

    case 'reject':
        if ($role !== 'SUPERVISOR') exit;
        $conn->query("
            UPDATE projects
            SET approval_status = 6,
                approval_updated_at = NOW()
            WHERE id = $project_id
        ");
        $_settings->audit('projects','rejected',"Supervisor rechaz¨® proyecto $project_id");
        break;

    /* =========================
       NUEVO: ASIGNAR GESTOR PMO
       ========================= */

    case 'assign_gestor':
        if (!in_array($role, ['ADMIN','SUPERVISOR'])) exit;

        $gestor_id = (int)$_POST['gestor_pmo_id'];

        $conn->query("
            UPDATE projects
            SET gestor_pmo_id = $gestor_id
            WHERE id = $project_id
        ");

        $_settings->audit(
            'projects',
            'assign_gestor',
            "Asignado Gestor PMO ($gestor_id) al proyecto $project_id"
        );
        break;
}

header("Location: view_project.php?id=$project_id");
exit;
