isLoggedIn()) { throw new Exception('Unauthorized'); } // Check if user is admin (only admins can approve/decline directives) if (!$auth->isAdmin()) { throw new Exception('Admin access required'); } $input = json_decode(file_get_contents('php://input'), true); if (!isset($input['id']) || !isset($input['status'])) { throw new Exception('Missing required parameters: id and status'); } $id = (int)$input['id']; $status = $input['status']; // Validate status if (!in_array($status, ['pending', 'approved', 'declined'])) { throw new Exception('Invalid status. Must be: pending, approved, or declined'); } $db = Database::getInstance(); // First, verify the directive exists and is impossible $checkStmt = $db->prepare(" SELECT id, is_impossible, status, attribute1_name, choice1, attribute2_name, choice2 FROM panel_directives WHERE id = ? AND llm_checked = 1 AND is_impossible = 1 "); $checkStmt->bind_param('i', $id); $checkStmt->execute(); $directive = $checkStmt->get_result()->fetch_assoc(); if (!$directive) { throw new Exception('Directive not found or not marked as impossible'); } // Check if status is actually changing if ($directive['status'] === $status) { echo json_encode([ 'success' => true, 'message' => 'Status is already set to ' . $status, 'directive' => [ 'id' => $id, 'status' => $status, 'combination' => $directive['attribute1_name'] . ' = ' . $directive['choice1'] . ' + ' . $directive['attribute2_name'] . ' = ' . $directive['choice2'] ] ]); exit; } // Update directive status $updateStmt = $db->prepare(" UPDATE panel_directives SET status = ?, updated_at = NOW() WHERE id = ? "); $updateStmt->bind_param('si', $status, $id); if (!$updateStmt->execute()) { throw new Exception('Failed to update directive status'); } // Log the status change for audit purposes $logStmt = $db->prepare(" INSERT INTO directive_status_log (directive_id, old_status, new_status, changed_by, changed_at) VALUES (?, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE old_status = VALUES(old_status), new_status = VALUES(new_status), changed_by = VALUES(changed_by), changed_at = VALUES(changed_at) "); if ($logStmt) { $logStmt->bind_param('issi', $id, $directive['status'], $status, $_SESSION['user_id']); $logStmt->execute(); } echo json_encode([ 'success' => true, 'message' => 'Directive status updated successfully', 'directive' => [ 'id' => $id, 'old_status' => $directive['status'], 'new_status' => $status, 'combination' => $directive['attribute1_name'] . ' = ' . $directive['choice1'] . ' + ' . $directive['attribute2_name'] . ' = ' . $directive['choice2'] ] ]); } catch (Exception $e) { http_response_code(500); echo json_encode([ 'success' => false, 'message' => $e->getMessage(), 'error_code' => 'DIRECTIVE_UPDATE_FAILED' ]); }